<?php

/**
 * This is the model class for table "sip_accounts".
 *
 * The followings are the available columns in table 'sip_accounts':
 * @property integer $id
 * @property string $authname
 * @property string $subnet
 * @property string $secret
 * @property string $current_ip
 * @property string $device_name
 * @property string $location
 * @property string $last_contact
 * @property integer $expires
 * @property string $state
 * @property integer $user_id
 */
class SipAccounts extends PhonalisaRecord
{

    public $id;
    public $authname;
    public $subnet;
    public $secret;
    public $current_ip;
    public $device_name;
    public $location;
    public $last_contact;
    public $expires;
    public $state;
    public $user_id;

    public static function myAttributes()
    {
        return array(
            'authname' => 'authname',
            'subnet' => 'subnet',
            'secret' => 'secret',
            'current_ip' => 'current_ip',
            'device_name' => 'device_name',
            'location' => 'location',
            'last_contact' => 'last_contact',
            'expires' => 'expires',
            'state' => 'state',
            'user_id' => 'user_id',
        );
    }

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

    /**
     * @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('authname, secret', 'required'),
            array('authname', 'ext.PhonalisaValidators.uniqueAuthName'),
            array('expires', 'numerical', 'integerOnly' => true),
            array('authname, subnet, location', 'length', 'max' => 255),
            array('secret', 'length', 'max' => 40),
            array('current_ip', 'length', 'max' => 16),
            array('device_name, user_id', 'length', 'max' => 64),
            array('state', 'length', 'max' => 10),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, authname, subnet, secret, current_ip, device_name, location, last_contact, expires, state, user_id', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @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(
            'user_id' => array(self::BELONGS_TO, 'User', 'id')
        );
    }

    public function beforeDelete()
    {
        // Find phones provisioned to this account!
        $phones = $this->getPhones();
        if ($phones != NULL) {
            foreach ($phones as $phone) {
                $phone->loggout();
            }
        }

        return parent::beforeDelete();
    }

    public function getSIPRegistrar()
    {
        return cfg('SIP_HOST');
    }

    public function getNTP()
    {
        return cfg('NTP_HOST');
    }

    public function getLabel()
    {
        //FIXMEFIXMEFIXME
        return $this->getDisplayName();
    }

    public function getShortLabel($numberFirst = false)
    {
        $user = User::model()->findByPk($this->user_id);
        if ($user == NULL) {
            return $this->authname;
        }

        $shortLabel = "";
        if ($numberFirst == true) {
            $shortLabel .= $user->extension . " ";
        }

        if ($user->firstname != "") {
            $shortLabel .= substr($user->firstname, 0, 1) . ".";
        }

        $maxLenght = 11 - strlen($user->extension);
        if ($user->lastname != "") {
            $shortLabel .= substr($user->lastname, 0, $maxLenght);
        }

        if ($numberFirst == false) {
            if ($shortLabel != "") {
                $shortLabel .= " ";
            }
            $shortLabel .= $user->extension;
        }

        return $shortLabel;
    }

    public function getDisplayName()
    {
        $user = User::model()->findByPk($this->user_id);
        if ($user != NULL) {
            return $user->getDisplayName();
        } else {
            return $this->authname;
        }
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => __('SIPACCOUNT_MODEL_ID'),
            'authname' => __('SIPACCOUNT_MODEL_AUTHNAME'),
            'subnet' => __('SIPACCOUNT_MODEL_SUBNET'),
            'secret' => __('SIPACCOUNT_MODEL_SECRET'),
            'current_ip' => __('SIPACCOUNT_MODEL_CURRENT_IP'),
            'device_name' => __('SIPACCOUNT_MODEL_DEVICE_NAME'),
            'location' => __('SIPACCOUNT_MODEL_LOCATION'),
            'last_contact' => __('SIPACCOUNT_MODEL_LAST_CONTACT'),
            'expires' => __('SIPACCOUNT_MODEL_EXPIRES'),
            'state' => __('SIPACCOUNT_MODEL_STATE'),
            'user_id' => __('SIPACCOUNT_MODEL_USER_ID'),
        );
    }

    /**
     * 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 = 'authname')
    {
        // 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('sip-accounts-grid'),
        );

        if ($filter != null) {
            return new CPhonalisaDataProvider($this, $filter
            );
        }
    }

    public function isUnique($attribute, $params)
    {
        $model = SipAccounts::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, __('SIPACCOUNT_IS_NOT_UNIQUE_ERROR_MESSAGE'));
        return false;
    }

    public function renderState(PhonalisaRecord $data, $row)
    {
        $path = Yii::app()->request->baseUrl;
        // check expired?
        if ((int) $data->last_contact + (int) $data->expires < time()) {
            $data->state = "";
            $data->save();
        }

        if ($data->state == "online") {
            echo '<span class="label label-success" data-sipaccountid="' . $data->id . '">Online</span>';
        } else {
            echo '<span class="label" data-sipaccountid="' . $data->id . '">N/a</span>';
        }
    }

    public function renderUser(PhonalisaRecord $data, $row)
    {
        if ($data->user_id) {

            $User = User::model()->findByPk($data->user_id);
            if ($User) {
                return $User->getDisplayName();
            }
        }

        return __("Nobody");
    }

    public function getUser()
    {
        $User = User::model()->findByPk($this->user_id);
        if ($User) {
            return $User;
        }
        return NULL;
    }

    //WARNING ! returns just the firts found Phones model
    public function getPhone()
    {
        $Phone = Phones::model()->findByAttributes(array("sip_account_id" => $this->id));
        if ($Phone) {
            return $Phone;
        }
        return NULL;
    }

    public function getPhones()
    {
        $phones = Phones::model()->findAllByAttributes(array("sip_account_id" => $this->id));
        if ($phones) {
            return $phones;
        }
        return NULL;
    }

    public function getLastPhones()
    {
        $phones = Phones::model()->findAllByAttributes(array("last_sip_account_id" => $this->id));
        if ($phones) {
            return $phones;
        }
        return NULL;
    }

    public function renderLastContact(PhonalisaRecord $data, $row)
    {
        if ((int) $data->last_contact == 0) {
            return __("n/a");
        }

        $relativeTime = RelativeDateFormatter::timeAgoInWords((int) $data->last_contact, array('format' => 'd.m.Y'));
        $regularTime = PhonalisaDate::userDateTime((int) $data->last_contact);

        return '<a href="#" rel="tooltip" title="' . $regularTime . '" data-placement="right">' . $relativeTime . '</a>';
    }

    //factory method to generate an standard sipaccount and assing this to an user object
    public static function generateSipAccountForUser($User)
    {
        //FIXME: Check if an sip account already exists and then add a,b,c etc. to the extension - 
        //       so we get multiple account support for Users. This is just currently not implemented 
        //       and we are not sure if we will implement this so far.	
        $sipaccount = new SipAccounts();
        $sipaccount->authname = $User->extension;
        $sipaccount->user_id = $User->id;
        $sipaccount->secret = PasswordGenerator::generateSipPassword();

        return $sipaccount;
    }

    public function humanReadableSearchFilterForUserID()
    {
        $models = SipAccounts::model()->findAll();
        $list = array();
        foreach ($models as $model) {
            if (!empty($model->user_id)) {
                $user = User::model()->findByPk($model->user_id);
                if ($user) {
                    $list[$model->user_id] = $user->getDisplayName();
                }
            }
        }
        $selected = '';
        if (isset($_REQUEST['SipAccounts']['user_id'])) {
            $selected = $_REQUEST['SipAccounts']['user_id'];
        }

        asort($list);
        return $list;
    }

    public function beforeSave()
    {
        if ($this->scenario == 'create' || $this->scenario == 'expireRangeChange') {
            $this->expires = $this->getStandardExpireTime();
        }
        return parent::beforeSave();
    }

    public function getStandardExpireTime()
    {
        $configExpireTime = cfg('STANDARD_EXPIRE_TIME');
        $expireTime = $configExpireTime;

        $configExpireTimePool = explode('-', $configExpireTime);
        if (!empty($configExpireTimePool[1])) {
            $expireStartTime = trim($configExpireTimePool[0]);
            $expireEndTime = trim($configExpireTimePool[1]);
            $expireTime = mt_rand($expireStartTime, $expireEndTime);
        }
        return "$expireTime";
    }

    public function renderCurrentIP(PhonalisaRecord $data)
    {
        if (filter_var($data->current_ip, FILTER_VALIDATE_IP)) {
            if (startsWith(strtolower($data->device_name), "openstage") || startsWith(strtolower($data->device_name), "siemens openstage")) {
                $ip = "https://" . $data->current_ip;
            } else {
                $ip = "http://" . $data->current_ip;
            }
            return CHtml::tag("a", array("target" => "_blank", "href" => $ip), $data->current_ip);
        }
        return $data->current_ip;
    }
}
