<?php

class CallGroup extends PhonalisaRecord
{

    public $id;
    public $name;
    public $extension;
    public $description;
    public $playlistId;
    public $target_on_timeout;
    public $target_type_on_timeout;
    public $target_on_timeout_meta;
    public $target_on_busy;
    public $target_type_on_busy;
    public $target_on_busy_meta;
    public $target_on_nightcircut;
    public $target_type_on_nightcircut;
    public $target_on_nightcircut_meta;
    public $target_on_empty;
    public $target_type_on_empty;
    public $target_on_empty_meta;
    public $max_hold_time;
    public $default_ring_time;
    public $night_circut;
    public $scriptExtension;

    public static function myAttributes()
    {

        return array(
            'id' => 'id',
            'name' => 'name',
            'extension' => 'extension',
            'description' => 'description',
            'playlistId' => 'playlistId',
            'target_on_timeout' => 'target_on_timeout',
            'target_type_on_timeout' => 'target_type_on_timeout',
            'target_on_timeout_meta' => 'target_on_timeout_meta',
            'target_on_busy' => 'target_on_busy',
            'target_type_on_busy' => 'target_type_on_busy',
            'target_on_busy_meta' => 'target_on_busy_meta',
            'target_on_nightcircut' => 'target_on_nightcircut',
            'target_type_on_nightcircut' => 'target_type_on_nightcircut',
            'target_on_nightcircut_meta' => 'target_on_nightcircut_meta',
            'target_on_empty' => 'target_on_empty',
            'target_type_on_empty' => 'target_type_on_empty',
            'target_on_empty_meta' => 'target_on_empty_meta',
            'max_hold_time' => 'max_hold_time',
            'default_ring_time' => 'default_ring_time',
            'night_circut' => 'night_circut',
            'scriptExtension' => 'scriptExtension'
        );
    }

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

    /**
     * @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, extension', 'required'),
            array('night_circut', 'boolean'),
            array('name', 'ext.PhonalisaValidators.isUnique'),
            array('extension, max_hold_time, default_ring_time', 'numerical', 'integerOnly' => true),
            array('extension', 'length', 'min' => 2, 'max' => 10),
            array('extension', 'ext.PhonalisaValidators.uniqueExtension'),
            array(
                'extension, max_hold_time, default_ring_time',
                'match',
                'pattern' => '/^[1-9]/',
                'message' => __('USER_MODEL_SHOULD_NOT_START_WITH_ZERO_ERROR_MESSAGE')
            ),
            array('max_hold_time, default_ring_time', 'length', 'max' => 3),
            array('name', 'length', 'max' => 40),
            array('id, description, playlistId', 'length', 'max' => 255),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, extension, name, description, playlistId, night_circut', 'safe', 'on' => 'search'),
            array('target_type_on_timeout,'
                . 'target_on_timeout,'
                . 'target_on_timeout_meta,'
                . 'target_type_on_busy,'
                . 'target_on_busy,'
                . 'target_on_busy_meta,'
                . 'target_type_on_nightcircut,'
                . 'target_on_nightcircut,'
                . 'target_on_nightcircut_meta,'
                . 'target_on_empty,'
                . 'target_type_on_empty,'
                . 'target_on_empty_meta'
                . 'playlistId,'
                . 'max_hold_time,'
                . 'default_ring_time,'
                . 'scriptExtension',
                'safe'
            ),
        );
    }

    /**
     * @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' => __('GLOBAL_ID'),
            'name' => __('ROUTING_CALL_GROUP_MODEL_NAME'),
            'description' => __('ROUTING_CALL_GROUP_MODEL_DESCRIPTION'),
            'playlistId' => __('ROUTING_CALL_GROUP_MODEL_PLAYLIST_ID'),
            'target_type_on_timeout' => __("ROUTING_CALL_GROUP_MODEL_TYPE_TARGET_ON_TIMEOUT"),
            'target_on_timeout' => __('ROUTING_CALL_GROUP_MODEL_TARGET_ON_TIMEOUT'),
            'target_on_timeout_meta' => __('ROUTING_CALL_GROUP_MODEL_TARGET_ON_TIMEOUT_META'),
            'target_type_on_busy' => __("ROUTING_CALL_GROUP_MODEL_TYPE_TARGET_ON_BUSY"),
            'target_on_busy' => __('ROUTING_CALL_GROUP_MODEL_TARGET_ON_BUSY'),
            'target_on_busy_meta' => __('ROUTING_CALL_GROUP_MODEL_TARGET_ON_BUSY_META'),
            'target_type_on_nightcircut' => __("ROUTING_CALL_GROUP_MODEL_TARGET_TYPE_ON_NIGHTCIRCUT"),
            'target_on_nightcircut' => __('ROUTING_CALL_GROUP_MODEL_TARGET_ON_NIGHTCIRCUT'),
            'target_on_nightcircut_meta' => __('ROUTING_CALL_GROUP_MODEL_TARGET_ON_NIGHTCIRCUT_META'),
            'target_type_on_empty' => __("ROUTING_CALL_GROUP_MODEL_TARGET_TYPE_ON_EMPTY"),
            'target_on_empty' => __('ROUTING_CALL_GROUP_MODEL_TARGET_ON_EMPTY'),
            'target_on_empty_meta' => __('ROUTING_CALL_GROUP_MODEL_TARGET_ON_EMPTY_META'),
            'extension' => __('ROUTING_CALL_GROUP_MODEL_EXTENSION'),
            'night_circut' => __('ROUTING_CALL_GROUP_MODEL_NIGHT_CIRCUT'),
            'max_hold_time' => __('ROUTING_CALL_GROUP_MODEL_MAX_HOLD_TIME'),
            'default_ring_time' => __('ROUTING_CALL_GROUP_MODEL_DEFAULT_RING_TIME'),
            'scriptExtension' => __('USER_MODEL_SCRIPT_EXTENSION')
        );
    }

    public function search($order = 'name')
    {
        $criteria = new CDbCriteria();
        $filter = $this->getFilter($criteria, $order);
        if ($filter != null) {

            $dataprovider = new CPhonalisaDataProvider($this, $filter);
            $routingCallGroupMax = PhonalisaLicenseManager::routingCallGroupMax();
            if ($routingCallGroupMax >= 0) {
                $dataprovider->pagination->pageSize = $dataprovider->pagination->pageSize > $routingCallGroupMax ? $routingCallGroupMax : $dataprovider->pagination->pageSize;
                $dataprovider->totalItemCount = $dataprovider->totalItemCount > $routingCallGroupMax ? $routingCallGroupMax : $dataprovider->totalItemCount;
            }

            return $dataprovider;
        }
    }

    public function getUsers()
    {
        $userToCallGroupModels = UserToCallGroup::model()->findAllByAttributes(array('callGroupId' => $this->id));
        $users = array();
        foreach ($userToCallGroupModels as $userToCallGroupModel) {
            $user = $userToCallGroupModel->getUser();
            if ($user != NULL) {
                $users[] = $user;
            }
        }
        return $users;
    }

    public function getUserDataProvider($pagination = false)
    {
        $users = $this->getUsers();
        if (empty($users)) {
            $defaultUser = new User();
            $defaultUser->extension = 'default';
            $defaultUserArray = array($defaultUser);
            $users = array_merge($defaultUserArray, $users);
        }
        $arrayDataProvider = new CArrayDataProvider($users, array('pagination' => $pagination));
        $arrayDataProvider->sort = $this->getCustomSortForArrayDataProvider();
        return $arrayDataProvider;
    }

    private function getCustomSortForArrayDataProvider()
    {
        $sort = new CSort();
        $sort->defaultOrder = 'name ASC';
        return $sort;
    }

    public function renderMemberDropdown()
    {
        $allUsers = User::model()->find(array(), 'name');
        $availableUsers = array();
        foreach ($allUsers as $user) {
            $userHasRelationToCallGroup = UserToCallGroup::model()->findAllByAttributes(array('userId' => $user->id, 'callGroupId' => $this->id));
            if (!$userHasRelationToCallGroup) {
                $availableUsers[$user->extension . "_" . $user->id . "_" . $user->name . "_" . $user->firstname . "_" . $user->lastname] = getFormatedUsername($user);
            }
        }
        return CHtml::dropDownList('memberDropdown', '', $availableUsers);
    }

    public function getMusicOnHoldList()
    {
        $playlistModel = new MusicOnHold();
        $data = CHtml::listData($playlistModel->find(array(), 'name'), 'id', 'name');
        $ldata['0'] = __("ROUTING_CALL_GROUP_RING_INSTEAD_OF_MUSIC");
        $ldata['default'] = __("DEFAULT_MOH_PLAYLIST_NAME");
        return array_merge($ldata, $data);
    }

    public function getTargetList()
    {
        $targetHelper = new TargetHelper;
        $targetList = $targetHelper->getRedirectionTargetList();
        $targetList = $this->removeCurrentCallGroupFromTargetList($targetList);
        return array_merge(array('_' => '---'), $targetList);
    }

    protected function removeCurrentCallGroupFromTargetList($targetList)
    {
        if (isset($targetList[__('CALL_GROUP')]['13_' . $this->id])) {
            unset($targetList[__('CALL_GROUP')]['13_' . $this->id]);
            if (empty($targetList[__('CALL_GROUP')])) {
                unset($targetList[__('CALL_GROUP')]);
            }
        }
        return $targetList;
    }

    public function getSelectedValueForTarget($targetAttribute)
    {
        $targetHelper = new TargetHelper();
        $typeAttribute = $this->getTypeAttributeForTargetAttribute($targetAttribute);
        $result = $targetHelper->getSelectedValueForAttributes($typeAttribute, $targetAttribute, $this);
        if ($this->$typeAttribute == TargetType::Manual) {
            $result = $this->$typeAttribute;
        }
        return $result;
    }

    protected function getTypeAttributeForTargetAttribute($targetAttribute)
    {
        $result = explode('_', $targetAttribute);
        return $result[0] . '_type_' . $result[1] . '_' . $result[2];
    }

    public function renderActiveNightCircut(PhonalisaRecord $data, $row)
    {
        $active = '<span class="icon-remove"></span>';
        if ($data->night_circut == '1') {
            $active = '<span class="icon-ok"></span>';
        }
        return $active;
    }

    public function renderPlayListID(PhonalisaRecord $data, $row)
    {
        $result = '';
        if ($data->playlistId == 'default') {
            $result = __('DEFAULT_MOH_PLAYLIST_NAME');
        } else {
            $result = $this->getMusicOnHoldName($data->playlistId);
        }
        return $result;
    }

    protected function getMusicOnHoldName($id)
    {
        $result = '';
        $model = MusicOnHold::model()->findByPk($id);
        if ($model == NULL) {
            $result = __('ROUTING_CALL_GROUP_RING_INSTEAD_OF_MUSIC');
        } else {
            $result = $model->name;
        }
        return $result;
    }

    public function getMaxHoldTime()
    {
        $maxHoldTime = $this->max_hold_time;
        if (empty($maxHoldTime)) {
            $maxHoldTime = 100;
        }
        return $maxHoldTime;
    }

    public function getDefaultMaxSliderTime()
    {
        $defaultTime = $this->default_ring_time;
        if (empty($defaultTime)) {
            $defaultTime = $this->getMaxHoldTime() / 2;
        }
        return $defaultTime;
    }

    public function getUserNumber()
    {
        return UserToCallGroup::model()->countAllByAttributes(array('callGroupId' => $this->id));
    }

    public function humanReadableSearchFilterForPlaylistID()
    {
        $models = MusicOnHold::model()->find(array(), 'name');
        $list = array(
            '0' => __('ROUTING_CALL_GROUP_RING_INSTEAD_OF_MUSIC'),
            'default' => __("DEFAULT_MOH_PLAYLIST_NAME")
        );
        foreach ($models as $playlist) {
            $list[$playlist->id] = $playlist->name;
        }
        return $list;
    }

    public function callGroupAddressbookProvider()
    {
        $addressbooks = Addressbook::model()->findAll();
        $filterBooks = array();
        foreach ($addressbooks as $addressbook) {
            if ($addressbook->type != AddressbookType::personal) {
                $filterBooks[] = $addressbook;
            }
        }
        return new CArrayDataProvider($filterBooks, array('pagination' => false));
    }
}
