<?php

class NotificationSettingController 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)
  {
    access_denied_check("notification_setting_management");
    return parent::beforeAction($event);
  }

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

  public function actionSwitchSound($id=null, $returnUrl=null)
  {
    access_denied_check("notification_setting_update_base");
    $model = $this->loadModel($id);
    $model->sound = $model->sound == 1 ? 0 : 1;
    $model->save();
    $this->redirect(empty($returnUrl) ? url("notificationSetting/admin") : $returnUrl);
  }

  public function actionSwitchPopup($id=null, $returnUrl=null)
  {
    access_denied_check("notification_setting_update_base");
    $model = $this->loadModel($id);
    $model->popup = $model->popup == 1 ? 0 : 1;
    $model->save();
    $this->redirect(empty($returnUrl) ? url("notificationSetting/admin") : $returnUrl);
  }

  public function actionSwitchEnabled($id=null, $returnUrl=null)
  {
    access_denied_check("notification_setting_update_base");
    $model = $this->loadModel($id);
    $model->enabled = $model->enabled == 1 ? 0 : 1;
    $model->save();
    $this->redirect(empty($returnUrl) ? url("notificationSetting/admin") : $returnUrl);
  }

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

    $model->epoch = DateTimeEx::nows();
    
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['NotificationSetting']))
    {
      $model->attributes=$_POST['NotificationSetting'];

      if(!user()->checkAccess('notification_setting_management_advanced'))
      {
        $model->target_id = user()->id;
        $model->target_type = NotificationSetting::TARGET_TYPE_USER;
        $model->endpoint_type = NotificationSetting::ENDPOINT_TYPE_WEB;
      }

      if($model->save())
        $this->redirect(array('view','id'=>$model->id));
    }
    else
    {
      $model->target_id = user()->id;
      $model->target_type = NotificationSetting::TARGET_TYPE_USER;
      $model->object_table = NotificationSetting::OBJECT_TABLE_EVENT_REPORTING;
      $model->filter_type = NotificationSetting::FILTER_TYPE_ANY;
      $model->endpoint_type = NotificationSetting::ENDPOINT_TYPE_WEB;
      $model->level = NotificationSetting::LEVEL_NORMAL;
      $model->sound = NotificationSetting::SOUND_DISABLED;
      $model->popup = NotificationSetting::POPUP_NO;
      $model->epoch = DateTimeEx::nows();
    }

    $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)
  {
    access_denied_check("notification_setting_update");
    $model=$this->loadModel($id);

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

    if(isset($_POST['NotificationSetting']))
    {
      $model->attributes=$_POST['NotificationSetting'];
      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)
  {
    access_denied_check("notification_setting_delete");
    if(!Yii::app()->request->isPostRequest && !user()->checkAccess("notification_setting_management_full"))
      throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

    $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'));
  }

  /**
   * Lists all models.
   */
  public function actionIndex()
  {
    $this->redirect(url('NotificationSetting/admin'));
  }

  /**
   * Manages all models.
   */
  public function actionAdmin()
  {
    $model=new NotificationSetting('search');
    $model->unsetAttributes();  // clear any default values
    if(isset($_GET['NotificationSetting']))
      $model->attributes=$_GET['NotificationSetting'];

    if(!user()->checkAccess('notification_setting_management_full'))
    {
      $model->onlyForCurrentUser = true;
    }

    $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
   * @return NotificationSetting the loaded setting
   */
  public function loadModel($id)
  {
    $model=NotificationSetting::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-setting-form')
    {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }

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

    if(isEmpty($params->action))
      throw new CHttpException(400,"Missing 'action' parameter.");

    if(!method_exists('NotificationSettingController',$params->action))
      throw new CHttpException(400,"Action '$params->action' does not exist.");

    $returnValue = call_user_func_array(array('NotificationSettingController',$params->action),array());

    echo(CJSON::encode($returnValue));

    app()->end();
  }

  public static function getSoundsArray()
  {
    $sounds = array();
    $sounds[NotificationSetting::SOUND_DISABLED] = t('No');
     
    $notificationSoundsPath = pathCombine(app()->basePath,'..','audio','notification');
    foreach(getFiles($notificationSoundsPath) as $audioFile)
    {
      $sounds[basename($audioFile)] = basename($audioFile);
    }
     
    return $sounds;
  }

  public static function getTargetTypesArray($index=null)
  {
    $data = array(
        NotificationSetting::TARGET_TYPE_USER=>t('User'),
    );
    return ($index===null)?$data:$data[$index];
  }

  public static function getTargetTypesIdsArray($index=null,$index0=null)
  {
    $targetTypes = self::getTargetTypesArray();
    $targetIds = array();
    foreach($targetTypes as $tk => $tl)
    {
      $ids = array();
       
      if($tk == NotificationSetting::TARGET_TYPE_USER)
      {
        if(user()->checkAccess('notification_setting_management_full'))
        foreach(User::model()->findAll() as $u)
          $ids[$u->id] = $u->username;
        else
          $ids[user()->model->id] = user()->model->username;
      }

      $targetIds[$tk] = $ids;
    }
    if($index!==null && $index0!==null)
      return $targetIds[$index][$index0];
    if($index!==null)
      return $targetIds[$index];
    return $targetIds;
  }

  public static function getObjectTablesArray($index=null)
  {
    $data = array(
        NotificationSetting::OBJECT_TABLE_EVENT_REPORTING=>t('Alert'),
    );
    return ($index===null)?$data:$data[$index];
  }

  public static function getEndpointTypesArray($index=null)
  {
    $data = array(
        NotificationSetting::ENDPOINT_TYPE_WEB=>t('Web'),
    );
    return ($index===null)?$data:$data[$index];
  }

  public static function getPopupArray($index=null)
  {
    $data =  array(
        NotificationSetting::POPUP_NO=>t('No'),
        NotificationSetting::POPUP_YES=>t('Yes'),
    );
    return ($index===null)?$data:$data[$index];
  }

  public static function getLevelsArray($index=null)
  {
    $data =  array(
        //NotificationSetting::LEVEL_URGENT=>t('Urgent'),
        //NotificationSetting::LEVEL_HIGH=>t('High'),
        NotificationSetting::LEVEL_NORMAL=>t('Normal'),
        //NotificationSetting::LEVEL_LOW=>t('Low'),
    );
    return ($index===null)?$data:$data[$index];
  }

  public static function getFilterTypesArray($index=null)
  {
    $data =  array(
        NotificationSetting::FILTER_TYPE_ANY =>t('Any'),
        NotificationSetting::FILTER_TYPE_BLACKLIST =>t('Blacklist'),
        NotificationSetting::FILTER_TYPE_BLACKLIST_ON_LIST =>t('Blacklist on list'),
        NotificationSetting::FILTER_TYPE_BLACKLIST_ON_PLATE =>t('Blacklist on plate'),
    );

    $canAccessFilters = user()->checkAccess('notification_setting_filter');

    $data = array_set_if($data, $canAccessFilters, NotificationSetting::FILTER_TYPE_PHP, 'PHP');
    $data = array_set_if($data, $canAccessFilters, NotificationSetting::FILTER_TYPE_CS, 'C#');
    $data = array_set_if($data, $canAccessFilters, NotificationSetting::FILTER_TYPE_SQL, 'SQL');

    return ($index===null)?$data:$data[$index];
  }
}
