<?php

/**
 * This is the model class for table "notification_setting".
 *
 * The followings are the available columns in table 'notification_setting':
 * @property string $id
 * @property string $description description of the setting
 * @property integer $enabled tell if the settings should be considered active
 * @property string $target_id id of the target user/list/system...
 * @property string $target_type type of target that should receive the notification (user,list/system....)
 * @property string $object_table table where to find the notified object
 * @property string $endpoint_type type of channel used to notify the target
 * @property string $endpoint_address optional address to be used to notify the target instead of the default one
 * @property integer $sound should be played a sound?
 * @property integer $popup should be displayed a popup
 * @property integer $level level of priority (low,normal,high,urgent), could modify how the notification is done
 * @property string $filter filter applied on the object_table (and linked tables) to create the right notification and dump the other rows
 * @property string $filter_type type of filter applied should be a preset or a custom sql/c#/php filter
 * @property string $epoch
 *
 * @property Notification[] notifications
 */
class NotificationSetting extends ActiveRecord
{
  const TARGET_TYPE_BROADCAST = "broadcast";
  const TARGET_TYPE_USER = "users";

  const OBJECT_TABLE_EVENT_REPORTING = "event_reporting";

  const ENDPOINT_TYPE_WEB = "web";
  const ENDPOINT_TYPE_MAIL = "mail";

  const SOUND_DISABLED = "no";

  const POPUP_NO  = 0;
  const POPUP_YES = 1;

  const LEVEL_URGENT = 100;
  const LEVEL_HIGH = 10;
  const LEVEL_NORMAL = 0;
  const LEVEL_LOW = -10;

  const FILTER_TYPE_SQL = 'sql';
  const FILTER_TYPE_CS  = 'cs';
  const FILTER_TYPE_PHP  = 'php';

  const FILTER_TYPE_ANY  = 'any';
  const FILTER_TYPE_BLACKLIST  = 'blacklist';
  const FILTER_TYPE_BLACKLIST_ON_LIST  = 'blacklist_list';
  const FILTER_TYPE_BLACKLIST_ON_PLATE  = 'blacklist_plate';

  /***************************/
  /****SEARCH FIELDS**********/
  /***************************/
  public $onlyForCurrentUser = false;
  /***************************/

  /**
   * Returns the static model of the specified AR class.
   * @param string $className active record class name.
   * @return NotificationSetting the static model class
   */
  public static function model($className=__CLASS__)
  {
    return parent::model($className);
  }

  /**
   * @return string the associated database table name
   */
  public function tableName()
  {
    return 'notification_setting';
  }

  /**
   * @return array validation rules for model attributes.
   */
  public function rules()
  {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('target_id, object_table, epoch', 'required'),
        array('enabled, sound, popup, level', 'numerical', 'integerOnly'=>true),
        array('description, target_type, object_table, endpoint_type, endpoint_address, filter_type', 'length', 'max'=>255),
        array('target_id', 'length', 'max'=>10),
        array('filter', 'safe'),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array('id, description, enabled, target_id, target_type, object_table, endpoint_type, endpoint_address, sound, popup, level, filter, filter_type, epoch', 'safe', 'on'=>'search'),
    );
  }

  /**
   * @return array relational rules.
   */
  public function relations()
  {
    return array(
        'notifications' => array(self::HAS_MANY, 'Notification', 'setting_id'),
    );
  }

  /**
   * @return array customized attribute labels (name=>label)
   */
  public function myAttributeLabels()
  {
    return array(
        'id' => 'ID',
        'description' => t('Description'),
        'enabled' => t('Enabled'),
        'target_id' => t('Target'),
        'target_type' => t('Target Type'),
        'object_table' => t('Object Table'),
        'endpoint_type' => t('Endpoint Type'),
        'endpoint_address' => t('Endpoint Address'),
        'sound' => t('Sound'),
        'popup' => t('Popup'),
        'level' => t('Level'),
        'epoch' => t('Epoch'),
        'filter' => t('Filter'),
        'filter_type' => t('Filter Type'),
    );
  }

  /**
   * Retrieves a list of models based on the current search/filter conditions.
   * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
   */
  public function search()
  {
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.
  
    $criteria=new CDbCriteria;
  
    $criteria->compare('id',$this->id,true);
    $criteria->compare('description',$this->description,true);
    $criteria->compare('enabled',$this->enabled);
    $criteria->compare('target_id',$this->target_id,true);
    $criteria->compare('target_type',$this->target_type,true);
    $criteria->compare('object_table',$this->object_table,true);
    $criteria->compare('endpoint_type',$this->endpoint_type,true);
    $criteria->compare('endpoint_address',$this->endpoint_address,true);
    $criteria->compare('sound',$this->sound);
    $criteria->compare('popup',$this->popup);
    $criteria->compare('level',$this->level);
    $criteria->compare('filter',$this->filter,true);
    $criteria->compare('filter_type',$this->filter_type,true);
    $criteria->compare('epoch',$this->epoch,true);
  
    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
  }

  /**
   * Retrieves a list of models based on the current search/filter conditions.
   * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
   */
  public function searchForGrid()
  {
    $criteria=new CDbCriteria;
    
    $criteria->compare('description',$this->description,true);
    
    if(!isEmpty($this->target_id))
    {
      // solo per utenti, per ora
      $users = null;
      if($this->onlyForCurrentUser)
        $users = array(user()->id=>user()->model);
      else
        $users = User::model()->findAll();
      
      $nsids = array();
      foreach ($users as $u)
      {
        if(containsStr($u->getFullName(),$this->target_id))
          $nsids[] = $u->id;
      }
      $criteria->addInCondition("target_id", $nsids);
    }
        
    if(!isEmpty($this->enabled))
    {
      if(containsStr(t('No'), $this->enabled))
        $criteria->addCondition("enabled<>1");
      if(containsStr(t('Yes'), $this->enabled))
        $criteria->addCondition("enabled=1");
    }    

    if(!isEmpty($this->sound))
    {
      if(containsStr(t('No'), $this->sound))
        $criteria->addCondition("sound<>1");
      if(containsStr(t('Yes'), $this->sound))
        $criteria->addCondition("sound=1");
    }    

    if(!isEmpty($this->popup))
    {
      if(containsStr(t('No'), $this->popup))
        $criteria->addCondition("popup<>1");
      if(containsStr(t('Yes'), $this->popup))
        $criteria->addCondition("popup=1");
    }

    if(!isEmpty($this->object_table))
    {
      $nsids = array();
      foreach (NotificationSettingController::getObjectTablesArray() as $objtabKey => $objtabLabel)
      {
        if(containsStr($objtabLabel,$this->object_table))
          $nsids[] = $objtabKey;
      }
      $criteria->addInCondition("object_table", $nsids);
    }

    if(!isEmpty($this->filter_type))
    {
      $nsids = array();
      foreach (NotificationSettingController::getFilterTypesArray() as $filtypeKey => $filtypeLabel)
      {
        if(containsStr($filtypeLabel,$this->filter_type))
          $nsids[] = $filtypeKey;
      }
      $criteria->addInCondition("filter_type", $nsids);
    }
    
    /*
    $criteria->compare('target_id',$this->target_id,true);
    $criteria->compare('target_type',$this->target_type,true);
    $criteria->compare('object_table',$this->object_table,true);
    $criteria->compare('endpoint_type',$this->endpoint_type,true);
    $criteria->compare('endpoint_address',$this->endpoint_address,true);
    $criteria->compare('level',$this->level);
    $criteria->compare('filter',$this->filter,true);
    $criteria->compare('filter_type',$this->filter_type,true);
    $criteria->compare('epoch',$this->epoch,true);
  */
    if($this->onlyForCurrentUser)
    {
      $criteria->addCondition("target_type='".self::TARGET_TYPE_USER."' AND target_id=".user()->id);
    }

    $provider = new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
    
    $provider->pagination->pageSize = 50;
    
    return $provider;
  }

  /**
   * le notifiche target_type=user e target_id=user()->id
   * @return NotificationSetting[] settings
   */
  public static function getUserNotificationSettings()
  {
    return NotificationSetting::model()->findAll(
        '(enabled+0)=:nbld AND ((target_type=:tt AND target_id=:uid))',
        array(
            ':tt'=>NotificationSetting::TARGET_TYPE_USER,
            ':uid'=>user()->id,
            ':nbld'=>1,
        ));
  }

  /**
   * le notifiche target_type=user e target_id=user()->id se non ha 'notification_setting_management_full' altrimenti tutte
   * @return NotificationSetting[] settings
   */
  public static function getVisibleToUserNotificationSettings()
  {
    if(!user()->checkAccess('notification_setting_management_full'))
    {
      return self::getUserNotificationSettings();
    }
    else
    {
      return NotificationSetting::model()->findAll();
    }
  }
}