<?php

class NotificationController extends Controller
{
  /**
   * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
   * using two-column layout. See 'protected/views/layouts/column2.php'.
   */
  public $layout='//layouts/column2';

  protected function beforeAction($event)
  {
    switch(strtolower($event->id))
    {
      case "get":
      case "view":
      case "dismiss":
      case "shown":
      case "setstreamisopen":
        access_denied_check("notification");
        break;
      default:
        access_denied_check("notification_management");
        break;
    }
    return parent::beforeAction($event);
  }

  /**
   * Displays a particular model.
   * @param integer $id the ID of the model to be displayed
   */
  public function actionView($id)
  {
    $this->render('view',array(
        'model'=>$this->loadModel($id),
    ));
  }

  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    $model=new Notification;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Notification']))
    {
      $model->attributes=$_POST['Notification'];
      if($model->save())
        $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
        'model'=>$model,
    ));
  }

  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   * @param integer $id the ID of the model to be updated
   */
  public function actionUpdate($id)
  {
    $model=$this->loadModel($id);

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Notification']))
    {
      $model->attributes=$_POST['Notification'];
      if($model->save())
        $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('update',array(
        'model'=>$model,
    ));
  }

  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   * @param integer $id the ID of the model to be deleted
   */
  public function actionDelete($id)
  {
    if(Yii::app()->request->isPostRequest)
    {
      // we only allow deletion via POST request
      $this->loadModel($id)->delete();

      // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
      if(!isset($_GET['ajax']))
        $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
    else
      throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
  }

  /**
   * Manages all models.
   */
  public function actionAdmin()
  {
    $model=new Notification('search');
    $model->unsetAttributes();  // clear any default values
    if(isset($_GET['Notification']))
      $model->attributes=$_GET['Notification'];
    
    if(!user()->checkAccess('notification_management_full'))
    {
      $model->onlyForCurrentUser = true;
    }
    
    if(!isEmpty($_REQUEST['setting_id']))
    {
      $model->specificSettingId = $_REQUEST['setting_id'];
    }
    
    $this->render('admin',array(
        'model'=>$model,
    ));
  }

  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer the ID of the model to be loaded
   */
  public function loadModel($id)
  {
    $model=Notification::model()->findByPk($id);
    if($model===null)
      throw new CHttpException(404,'The requested page does not exist.');
    return $model;
  }

  /**
   * Performs the AJAX validation.
   * @param CModel the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if(isset($_POST['ajax']) && $_POST['ajax']==='notification-form')
    {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }


  public function actionShown()
  {
    $req = new Request();
    if(!isEmpty($req->shown))
    {
      //logLine("actionShown: $req->shown");
      try
      {
        foreach(Notification::model()->findAll('id IN (:ids)',array(':ids'=>$req->shown)) as $n)
        {
          //logLine("found $n->id");
          $n->status = Notification::STATUS_SHOWN;
          $n->read = DateTimeEx::nows();
          if($n->save())
          {
            //logLine("done");
          }
          else
          {
            //logLine("error");
          }
        }
      }
      catch (Exception $e)
      {
        //logLine($e->getMessage());
      }
    }
  }

  public function actionDismiss($id)
  {
    //logLine("DISMISS $id");
    $n = Notification::model()->findByPk($id);
    if($n != null)
    {
      $n->status = Notification::STATUS_DISMISSED;
      $n->save();
    }
  }

  public function actionIndex()
  {
    $this->redirect(url('Notification/admin'));
  }

  public function actionGet()
  {
    $params = new CArray($_REQUEST);
    $notifications = array();

    $action = isEmpty($params->action) ? 'new' : strtolower($params->action);

    $popup = intval(SessionVars::instance()->streamIsOpen);
    $sound = 0;
    $ids = array();
    //logLine("////BEGIN");
    switch($action)
    {
      case 'new':

        $settings = NotificationSetting::getUserNotificationSettings();
         
        foreach($settings as $setting)
        {
          if($setting->endpoint_type == NotificationSetting::ENDPOINT_TYPE_WEB)
          {
            foreach($setting->notifications as $notification)// attenzione, da cambiare in Unread !!!
            {
              if($notification->status != Notification::STATUS_DISMISSED)
              {
                if(self::filterNotification($setting, $notification))
                {
                  $notifications[] = SystemInfoHelper::getNotificationHtml($setting, $notification);
                  //logLine("$notification->id");
                  if($notification->status != Notification::STATUS_SHOWN)
                  {
                    $ids[] = $notification->id;
                    $popup += intval($setting->popup);
                    $sound += intval($setting->sound);
                  }
                }
                else
                {
                  if(paramdeep('notification','deleteFiltered'))
                  {
                    $notification->delete();
                  }
                  else
                  {
                    $notification->status = Notification::STATUS_DUMPED;
                    $notification->save();
                  }
                }
              }
            }
          }
        }

        break;
    }

    // TEST
    //$test = DateTimeEx::nows();
    //$notifications[] = array('timestamp'=>DateTimeEx::nows(), 'content'=>$test);

    $html = $this->renderPartial('items',array('notifications'=>$notifications), true);

    $response = array();

    $response['shown_register'] = count($ids) > 0 ? 1 : 0;
    $response['shown_url'] = url('notification/shown',array('shown'=>implode(',', $ids)));

    $response['sound_url'] = url('/audio/notification/default.wav');
    $response['sound'] = $sound > 0 ? 1 : 0;

    $response['popup'] = $popup > 0 ? 1 : 0;

    $response['html'] = $html;

    $response['notification_count'] = count($notifications);

    $json = CJSON::encode($response);

    //logLine($sound);
    //logLine($json);
    //logLine("////END");

    echo($json);

    app()->end();
  }

  public static function filterNotification(NotificationSetting $setting, Notification $notification)
  {
    if($setting->object_table == NotificationSetting::OBJECT_TABLE_EVENT_REPORTING)
    {
      switch ($setting->filter_type)
      {
        case NotificationSetting::FILTER_TYPE_BLACKLIST:
          if($notification->object_id)
          {
            $alert = Alert::model()->findByPk($notification->object_id);
            if($alert != null)
            if($alert->behavior_tag==Behavior::BLACKLIST)
              return true;
          }
          break;
        case NotificationSetting::FILTER_TYPE_BLACKLIST_ON_LIST:
          if($notification->object_id)
          {
            $alert = Alert::model()->findByPk($notification->object_id);
            if($alert != null)
            if($alert->behavior_tag==Behavior::BLACKLIST)
            if(array_value_exists(explode(';', $alert->exta_data), $setting->filter))
              return true;
          }
          break;
        case NotificationSetting::FILTER_TYPE_BLACKLIST_ON_PLATE:
          if($notification->object_id)
          {
            $alert = Alert::model()->findByPk($notification->object_id);
            if($alert != null)
            if($alert->behavior_tag==Behavior::BLACKLIST)
            {
              $event = $alert->getAssociatedEvent();
              if($event != null && array_value_exists(explode(";", $setting->filter), $event->getPlate()))
                return true;
            }
          }
          break;
        case NotificationSetting::FILTER_TYPE_ANY:
          /*if($notification->object_id)
          {
            $alert = Alert::model()->findByPk($notification->object_id);
            if($alert != null)
            if($alert->behavior_tag==Behavior::BLACKLIST)
            {
              $event = $alert->getAssociatedEvent();
              if($event != null && array_value_exists(explode(";", $setting->filter), $event->getPlate()))
                return true;
            }
          }*/
          return true;
          break;
      }
    }
    return false;
  }

  public function actionSetStreamIsOpen()
  {
    $params = new CArray($_REQUEST);

    SessionVars::instance()->streamIsOpen = $params->isopen;
     
    app()->end();
  }
}
