<?php

class ExternalAgentState
{

    const offline = 0;
    const online = 1;

    public static function readable($type)
    {
        switch ($type) {
            case ExternalAgentState::online :
                return __('EXTERNAL_AGENT_TYPE_ONLINE');
            case ExternalAgentState::offline :
                return __('EXTERNAL_AGENT_TYPE_OFFLINE');
        }
    }
}

class ExternalAgentTypes
{

    const callback = 3;
    const standby = 4;

    public static function readable($type)
    {
        switch ($type) {
            case ExternalAgentTypes::callback :
                return __('EXTERNAL_AGENT_TYPE_CALLBACK');
            case ExternalAgentTypes::standby :
                return __('EXTERNAL_AGENT_TYPE_STANDBY');
        }
    }
}

class ExternalAgent extends PhonalisaRecord
{

    public $id;
    public $name;
    public $number;
    public $state = ExternalAgentState::online;
    public $type = ExternalAgentTypes::callback;
    public $pin;
    public $scriptExtension;

    public static function myAttributes()
    {

        return array(
            'name' => 'name', //  Name required
            'number' => 'number', //  Number required
            'type' => 'type', //  Type (Callback/Standby)
            'state' => 'state', //  State (Online/Offline)
            'pin' => 'pin',
            'scriptExtension' => 'scriptExtension'
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Calendar 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 strtolower('ExternalAgent');
    }

    /**
     * @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('name, number', 'required'),
            array('number', 'isUnique'),
            array('pin', 'numerical', 'integerOnly' => true),
            array('pin', 'length', 'min' => 3, 'max' => 10),
            array('state, type, scriptExtension', 'safe'),
        );
    }

    public function isUnique($attribute, $params)
    {
        $model = ExternalAgent::model()->findByAttributes(array($attribute => $this->$attribute));
        if (!$model) {
            return true;
        }
        if ($this->isNewRecord() && $this->$attribute != $model->$attribute) {
            return true;
        } else if (!$this->isNewRecord() && $model->id == $this->id) {
            return true;
        }
        $this->addError($attribute, __('USER_MODEL_IS_UNIQUE_ERROR_MESSAGE'));
        return false;
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => __('EXTERNAL_AGENT_MODEL_ID'),
            'name' => __('EXTERNAL_AGENT_MODEL_NAME'),
            'number' => __('EXTERNAL_AGENT_MODEL_NUMBER'),
            'type' => __('EXTERNAL_AGENT_MODEL_TYPE'),
            'state' => __('EXTERNAL_AGENT_MODEL_STATE'),
            'pin' => __('EXTERNAL_AGENT_MODEL_PIN'),
            'scriptExtension' => __('USER_MODEL_SCRIPT_EXTENSION')
        );
    }

    /**
     * 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($order = 'name')
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        $filter = $this->getFilter($criteria, $order);

        $filter['pagination'] = array(
            'pageSize' => getGridPageSize('external-agent-grid'),
        );

        if ($filter != null) {
            $dataProvider = new CPhonalisaDataProvider($this, array(
                'criteria' => $criteria,
            ));

            $routingExternalAgentsMax = PhonalisaLicenseManager::routingExternalAgentsMax();
            if ($routingExternalAgentsMax >= 0) {
                $dataProvider->pagination->pageSize = $dataProvider->pagination->pageSize > $routingExternalAgentsMax ? $routingExternalAgentsMax : $dataProvider->pagination->pageSize;
                $dataProvider->totalItemCount = $dataProvider->totalItemCount > $routingExternalAgentsMax ? $routingExternalAgentsMax : $dataProvider->totalItemCount;
            }
            return $dataProvider;
        }
    }

    public function getListData($attribute = 'type')
    {
        if ($attribute == 'type') {
            $data = array(
                'Callback' => array(
                    'value' => ExternalAgentTypes::callback,
                    'label' => 'Callback'
                ),
                'Standby' => array(
                    'value' => ExternalAgentTypes::standby,
                    'label' => 'Standby'
            ));
            $data = CHtml::listData($data, 'value', 'label');
            return $data;
        }
    }

    public function humanReadableSearchFilterForState()
    {
        $list = array(
            ExternalAgentState::online => ExternalAgentState::readable(ExternalAgentState::online),
            ExternalAgentState::offline => ExternalAgentState::readable(ExternalAgentState::offline)
        );
        return $list;
    }

    public function beforeDelete()
    {
        $tiers = Tiers::model()->findAllByAttributes(array("userId" => $this->id));
        foreach ($tiers as $tier) {
            $tier->delete();
        }
        return parent::beforeDelete();
    }

    public static function allowExternalAgentCreate()
    {
        $routingExternalAgentsMax = PhonalisaLicenseManager::routingExternalAgentsMax();
        if ((int) $routingExternalAgentsMax >= 0) {
            $routingExternalAgentsCount = ExternalAgent::model()->countByAttributes(array());
            if ((int) $routingExternalAgentsCount >= (int) $routingExternalAgentsMax) {
                return false;
            }
        }
        return true;
    }

    public function beforeSave()
    {
        if ($this->isNewRecord && !self::allowExternalAgentCreate()) {
            return false;
        }
        return parent::beforeSave();
    }
}
