<?php

require_once(dirname(realpath(__FILE__)) . '/../components/callforwarding/class.usercallforward.php');
require_once(dirname(realpath(__FILE__)) . '/../components/callforwarding/class.callforwardingfactory.php');

class ForwardPresetType
{

    const PrivatePreset = 0;
    const PublicPreset = 1;
    const SytemPreset = 2;

    public static function translateType($type)
    {
        if ($type == ForwardPresetType::PrivatePreset) {
            return __('CALLFORWARD_PRESET_TYPE_PRIVATE');
        } elseif ($type == ForwardPresetType::PublicPreset) {
            return __('CALLFORWARD_PRESET_TYPE_PUBLIC');
        } elseif ($type == ForwardPresetType::SytemPreset) {
            return __('CALLFORWARD_PRESET_TYPE_SYSTEM');
        }
    }
}

class ForwardType
{

    const Disabled = 0;
    const Immediately = 1;
    const Custom = 2;

    public static function translateType($type)
    {
        if ($type == ForwardType::Disabled) {
            return __('CALLFORWARD_TYPE_DISABLED');
        } elseif ($type == ForwardType::Immediately) {
            return __('CALLFORWARD_TYPE_IMMEDIATELY');
        } elseif ($type == ForwardType::Custom) {
            return __('CALLFORWARDT_TYPE_CUSTOM');
        }
    }
}

class ForwardPreset extends PhonalisaRecord
{

    public $name;
    public $description;
    public $type;
    public $forwardType;
    public $configs;
    public $owner;
    public $created;

    public static function myAttributes()
    {
        return array(
            'name' => 'name',
            'description' => 'description',
            'type' => 'type',
            'configs' => 'configs',
            'owner' => 'owner',
            'forwardType' => 'forwardType',
            'created' => 'created',
        );
    }

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

    /**
     * @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('type, name', 'required'),
            array('configs', 'required', 'on' => 'update'),
            array('type, configs, name, description, forwardType', '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(
            'name' => __('FORWARD_PRESET_MODEL_NAME'),
            'description' => __('FORWARD_PRESET_MODEL_DESCRIPTION'),
            'type' => __('FORWARD_PRESET_MODEL_TYPE'),
            'forwardType' => __('FORWARD_PRESET_MODEL_FORWARD_TYPE'),
            'configs' => __('FORWARD_PRESET_MODEL_CONFIGS'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CPhonalisaDataProvider the data provider that can return the models based on the
     * search/filter conditions.
     */
    public function search($order = 'type')
    {
        $criteria = new CDbCriteria;
        $filter = $this->getFilter($criteria, $order);
        if ($filter != null) {
            return new CPhonalisaDataProvider($this, $filter);
        }
    }

    public function getAvailableTypes()
    {
        return array(
            ForwardPresetType::PrivatePreset => ForwardPresetType::translateType(
                ForwardPresetType::PrivatePreset
            ),
            ForwardPresetType::PublicPreset => ForwardPresetType::translateType(
                ForwardPresetType::PublicPreset
            ),
        );
    }

    public function findAllByTypes($types = array())
    {
        $models = array();
        foreach ($types as $type) {
            $modelsOfType = ForwardPreset::model()->findAllByAttributes(
                array('type' => $type)
            );
            if ($modelsOfType != null) {
                $models = array_merge($models, $modelsOfType);
            }
        }
        return $models;
    }

    public function getPrivatePresets($userId)
    {
        return ForwardPreset::model()->findAllByAttributes(
            array(
                'type' => ForwardPresetType::PrivatePreset,
                'owner' => $userId
            )
        );
    }

    public function renderTypeBadge()
    {
        if ($this->type == ForwardPresetType::PrivatePreset) {
            return '<span '
                . 'class="label label-info" '
                . 'data-translation-id="CALLFORWARD_PRESET_TYPE_PRIVATE"'
                . '>'
                . ForwardPresetType::translateType($this->type) . '</span>';

        } elseif ($this->type == ForwardPresetType::PublicPreset) {
            return '<span '
                . 'class="label label-important" '
                . 'data-translation-id="CALLFORWARD_PRESET_TYPE_PUBLIC">'
                . ForwardPresetType::translateType($this->type)
                . '</span>';
        } elseif ($this->type == ForwardPresetType::SytemPreset) {
            return '<span '
                . 'class="label" data-translation-id="CALLFORWARD_PRESET_TYPE_SYSTEM"'
                . '>'
                . ForwardPresetType::translateType($this->type)
                . '</span>';
        }
    }

    public function getPhoneKeyModel()
    {
        $owner = app()->user->sudoUserInstance->id;
        if ($this->scenario == 'deleteUser') {
            $owner = $this->id;
        }
        return ForwardPresetPhoneKey::model()->findByAttributes(array(
                'owner' => $owner,
                'forwardPreset' => $this->id,
        ));
    }

    public function getSimpleTargetNumber($user = null)
    {

        if ($user == null) {
            $user = app()->user->sudoUserInstance;
        }

        $jsonString = base64_decode($this->configs);
        $jsonObject = json_decode($jsonString);
        $userFwd = CallForwardingFactory::getUserCallForwardFromJSONRepresentation($jsonObject, $user);


        $simpleFwd = $userFwd->getDefinedSimpleCallforward();
        $target = $simpleFwd->getCallForwardTarget();
        if ($target->getCallForwardType() == "number") {
            return $target->getProperty("number");
        }
        return "";
    }

    public function getPhoneKey()
    {
        $model = $this->getPhoneKeyModel();

        if ($model != null) {
            return $model->key;
        }

        return null;
    }

    public function deletePhoneKey()
    {
        $model = $this->getPhoneKeyModel();
        if ($model != null) {
            $model->delete();
        }
    }

    public function setPhoneKey($key)
    {
        $model = $this->getPhoneKeyModel();

        if ($model == null) {
            $model = new ForwardPresetPhoneKey();
        }

        $model->forwardPreset = $this->id;
        $model->key = $key;

        return $model->save();
    }

    public function deletePermissions()
    {
        $models = Permissions::model()->findAllByAttributes(
            array(
                'itemId' => $this->id
            )
        );

        foreach ($models as $model) {
            $model->delete();
        }
    }

    public function renderPhoneKeyInput()
    {
        $fieldName = "ForwardPreset[key][$this->id]";
        $inputFiled = CHtml::textField(
            $fieldName,
            $this->getPhoneKey(),
            array(
                "maxlength" => 1,
                "pattern" => "[0-9]",
                "onkeypress" => 'return event.charCode > 47 && event.charCode < 58;'
            )
        );

        $prepand = CHtml::tag(
            'span',
            array(
                'class' => 'add-on',
                'data-translation-id' => "FORWARD_PRESET_FEATURE_PHONE_KEY_INPUT_PREPEND"
            ),
            cfg("DP_FWD_ON_PREFIX")
        );


        return CHtml::tag(
            "div",
            array(
                'class' => 'input-prepend'
            ),
            $prepand . $inputFiled
        );
    }

    public function beforeDelete()
    {
        $this->deletePhoneKey();
        $this->deletePermissions();
        return parent::beforeDelete();
    }

    public function beforeSave()
    {
        if ($this->isNewRecord) {
            $this->created = date('Y-m-d G:i:s');
        }

        if ($this->forwardType == ForwardType::Disabled) {
            $this->configs = base64_encode(
                '{"active":"none","advanced":[],"simple":[],"possibleCriterias":{},"possibleTargets":[]}'
            );
        }
        return parent::beforeSave();
    }

    public function __toString()
    {
        return $this->id;
    }
}
