<?php

class FaxDeliveryStatus
{

    const undefined = 0;
    const Submitted = 1;
    const Preparing = 7;
    const Queued = 2;
    const Progress = 3;
    const Sent = 4;
    const Failed = 5;
    const GivingUp = 6;

    public static function translate($state)
    {
        $states = array(
            FaxDeliveryStatus::undefined => __('n/a'),
            FaxDeliveryStatus::Submitted => __('FAX_STATE_SUBMITTED'),
            FaxDeliveryStatus::Queued => __('FAX_STATE_QUEUED'),
            FaxDeliveryStatus::Progress => __('FAX_STATE_PROGRESS'),
            FaxDeliveryStatus::Sent => __('FAX_STATE_SENT'),
            FaxDeliveryStatus::Failed => __('FAX_STATE_FAILED'),
            FaxDeliveryStatus::GivingUp => __('FAX_STATE_GIVING_UP'),
        );

        if (array_key_exists($state, $states)) {
            return $states[$state];
        } else {
            return FaxDeliveryStatus::undefined;
        }
    }
}

class UCType
{

    const Call = 'call';
    const Fax = 'fax';
    const Email = 'email';
    const Callrecording = 'callrecording';
    const GroupCall = 'gcall';
    const CTIcall = 'cticall';
    const QueueCall = 'qcall';
    const GroupFax = 'gfax';

}

class UCDirection
{

    const Out = 0;
    const In = 1;

}

class UCState
{

    const Unkown = 0;
    const Ringing = 1;
    const Answered = 2;
    const Hangedup = 3;
    const Forwarded = 4;
    const Blindtransfered = 5;
    const Attendedtransfered = 6;
    const Missed = 7;
    const Success = 8;
    const Picked = 9;

}

class UCItem extends PhonalisaRecord
{

    public $fax_document_total_pages;
    public $fax_document_transferred_pages;
    public $fax_image_pixel_size;
    public $fax_image_resolution;
    public $fax_remote_station_id;
    public $fax_success;
    public $fax_transfer_rate;
    public $fax_content;
    public $voicemail_id;
    public $fax_number;
    public $fax_data;
    public $fax_data_file_type;
    public $fax_image_size;
    public $fax_result_code;
    public $fax_result_text;
    public $fax_header;
    public $fax_header_text;
    public $fax_header_number;
    public $direction;
    public $target;
    public $typ;
    public $id;
    public $state;
    public $from;
    public $to;
    public $data;
    public $timestamp;
    public $red;
    public $forwarded;
    public $answered;
    public $flagged;
    public $childs;
    public $duration;
    public $owner_id;
    public $owner_type;
    public $remote_number;
    public $remote_name;
    public $remote_type;
    public $remote_id;
    public $remote_avatar;
    public $rating;
    public $meta;
    public $caller_addressbook_id;
    public $fax_content_pdf;
    public $fax_content_png;
    public $tries;
    public $note;
    public $cent_price;
    public $group_extension;
    public $picked_by;
    public $answered_by;
    private $_interlocutor = null;
    public $callerName = null;

    public static function myAttributes()
    {

        return array(
            'id' => 'id',
            'fax_document_total_pages' => 'fax_document_total_pages',
            'fax_document_transferred_pages' => 'fax_document_transferred_pages',
            'fax_image_pixel_size' => 'fax_image_pixel_size',
            'fax_image_resolution' => 'fax_image_resolution',
            'fax_remote_station_id' => 'fax_remote_station_id',
            'fax_success' => 'fax_success',
            'fax_transfer_rate' => 'fax_transfer_rate',
            'fax_content' => 'fax_content',
            "fax_header_text" => "fax_header_text",
            "fax_header_number" => "fax_header_number",
            'tries' => 'tries',
            'direction' => 'direction',
            'typ' => 'typ',
            'state' => 'state',
            'from' => 'from',
            'to' => 'to',
            'data' => 'data',
            'timestamp' => 'timestamp',
            'red' => 'red',
            'forwarded' => 'forwarded',
            'answered' => 'answered',
            'flagged' => 'flagged',
            'childs' => 'childs',
            'duration' => 'duration',
            'owner_id' => 'owner_id',
            'owner_type' => 'owner_type',
            'remote_number' => 'remote_number',
            'remote_name' => 'remote_name',
            'remote_type' => 'remote_type',
            'remote_id' => 'remote_id',
            'remote_avatar' => 'remote_avatar',
            'rating' => 'rating',
            'meta' => 'meta',
            'caller_addressbook_id' => 'caller_addressbook_id',
            'fax_content_pdf' => 'fax_content_pdf',
            'fax_content_png' => 'fax_content_png',
            'voicemail_id' => 'voicemail_id',
            'fax_number' => 'fax_number',
            'fax_data' => 'fax_data',
            'fax_image_size' => 'fax_image_size',
            'fax_result_code' => 'fax_result_code',
            'fax_result_text' => 'fax_result_text',
            'target' => 'target',
            'note' => 'note',
            'cent_price' => 'cent_price',
            'group_extension' => 'group_extension',
            'picked_by' => 'picked_by',
            'answered_by' => 'answered_by'
        );
    }

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

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()//FIXME !!!!!
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            //array('fax_data','required','on'=>'createFax'),
            array('', 'required'),
            array('
                    remote_number, target,tries,remote_name,remote_type,
                    remote_id,remote_avatar,rating,meta,caller_addressbook_id,fax_content_pdf,fax_content_png,
                    voicemail_id,fax_number,fax_data,fax_image_size,fax_result_code,fax_result_text,target,
		            fax_document_total_pages,
                    fax_document_transferred_pages,
                    fax_image_pixel_size,
                    fax_image_resolution,
                    fax_remote_station_id,fax_success,
                    fax_transfer_rate,
                    fax_transfer_rate,
                    fax_content,
                    direction,
            		cent_price,
                    typ, state, from, to,
                    data, timestamp, red,
                    forwarded, answered,
                    flagged, childs,
                    duration, owner_id, owner_type,
            		fax_number, fax_header_text ,
            		group_extension,
            		fax_header_number,
            		answered_by,
            		picked_by', 'length', 'max' => 255),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array(
                'id,'
                . 'type,'
                . 'state,'
                . 'from,'
                . 'to,'
                . 'data,'
                . 'timestamp,'
                . 'red,'
                . 'forwarded,'
                . 'answered,'
                . 'flagged,'
                . 'childs,'
                . 'duration,'
                . 'owner,'
                . 'direction',
                'safe',
                'on' => 'search'
            ),
            array('fax_data', 'required', 'on' => 'sendFax'),
            array('fax_number', 'required', 'on' => 'sendFax')
        );
    }

    /**
     * @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' => __('ID'),
            'typ' => __('typ'),
            'state' => __('state'),
            'from' => __('from'),
            'to' => __('to'),
            'data' => __('data'),
            'timestamp' => __('timestamp'),
            'red' => __('red'),
            'forwarded' => __('forwarded'),
            'answered' => __('answered'),
            'flagged' => __('flagged'),
            'childs' => __('childs'),
            'duration' => __('duration'),
            'owner' => __('owner'),
            'direction' => __('direction'),
            'fax_number' => __('UCITEM_MODEL_FAX_NUMBER'),
            'fax_data' => __('UCITEM_MODEL_FAX_DATA'),
            'fax_header' => __('UCITEM_MODEL_FAX_HEADER'),
            'fax_header_text' => __('UCITEM_MODEL_FAX_HEADER_TEXT'),
            'fax_header_number' => __('UCITEM_MODEL_FAX_HEADER_NUMBER'),
            'note' => __('UCITEM_MODEL_NOTE'),
            'group_extension' => __('UCITEM_MODEL_GROUP_EXTENSION'),
            'picked_by' => __('UCITEM_MODEL_PICKED_BY'),
            'answered_by' => __('UCITEM_MODEL_ANSWERED_BY'),
        );
    }

    /**
     * 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);
        $criteria->compare('typ', $this->typ, true);
        $criteria->compare('state', $this->state, true);
        $criteria->compare('from', $this->from, true);
        $criteria->compare('to', $this->to, true);
        $criteria->compare('data', $this->data, true);
        $criteria->compare('timestamp', $this->timestamp);
        $criteria->compare('red', $this->red, true);
        $criteria->compare('forwarded', $this->forwarded, true);
        $criteria->compare('answered', $this->answered, true);
        $criteria->compare('flagged', $this->flagged, true);
        $criteria->compare('childs', $this->childs, true);
        $criteria->compare('duration', $this->duration, true);
        $criteria->compare('owner', $this->owner, true);
        $criteria->compare('direction', $this->owner, true);
        $criteria->compare('group_extension', $this->group_extension, true);

        return new CPhonalisaDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    private function getInterlocutor()
    {
        if ($this->_interlocutor == null && $this->caller_addressbook_id != null) {
            $this->_interlocutor = Addresses::model()->findByPk($this->caller_addressbook_id);
            if ($this->_interlocutor) {
                $this->checkPermissionsOnAddress();
            }
        }
        return $this->_interlocutor;
    }

    private function checkPermissionsOnAddress()
    {
        $permission = new Permissions();
        $permissions = $permission->getPermissionsArray(array("groupId" => User::getCurrentSudoUser()->group, "itemId" => $this->_interlocutor->contact_tid), true);
        if (empty($permissions)) {
            $this->_interlocutor = null;
        }
    }

    public function getInterlocutorName()
    {
        if ($this->callerName != null) {
            return $this->callerName;
        }

        if ($this->getInterlocutor() != null) {
            return $this->getInterlocutor()->formatedName;
        } else if ($this->caller_addressbook_id != null) {

            $this->caller_addressbook_id = null;
        }

        if ($this->typ == 'callrecording') {
            return null;
        }
        return 'n/a';
    }

    public function getAvatarUrl($size = 80)
    {
        $addressModel = null;

        if ($this->caller_addressbook_id != '') {
            $addressModel = Addresses::model()->findByPk($this->caller_addressbook_id);
        }

        if ($addressModel == null || $addressModel->contact_jpegphoto == '') {
            return bu() . '/img/backgrounds/noAvatar.png';
        }
        return $addressModel->getPhotoUrl($size);
    }

    public function getFaxPngUrls($limit = false)
    {
        $attributePrefix = 'fax_content_png_';

        $i = 1;
        $urlList = array();
        while ($this->valueForKey($attributePrefix . $i, false)) {
            $urlList[] = Yii::app()->createUrl('homeUCItem/default/faxPage', array('id' => $this->id, 'page' => $i));
            $i++;
        }
        return $urlList;
    }

    public function getPdfPreviewUrl()
    {
        return Yii::app()->createUrl('homeUCItem/default/renderFaxPage', array('id' => $this->id));
    }

    public function getVoicemailUrls()
    {
        $urls = array();
        if ($this->voicemail_id != null) {

            $urls['audio/wav'] = Yii::app()->createUrl(
                    'homeUCItem/default/getVoicemailFile', array(
                'id' => $this->voicemail_id,
                'type' => 'audio/wav'
                    )
            );
        } elseif ($this->typ == 'callrecording' || ($this->typ == 'call' && $this->valueForKey('record_data') != '')) {
            $urls['audio/wav'] = Yii::app()->createUrl(
                    'homeUCItem/default/getVoicemailFile', array(
                'id' => $this->id,
                'type' => 'audio/wav'
                    )
            );
        }
        $urls['audio/ogg'] = Yii::app()->createUrl(
                'homeUCItem/default/getVoicemailFile', array(
            'id' => $this->voicemail_id,
            'type' => 'audio/ogg'
                )
        );
        return $urls;
    }

    public function getFaxUrls()
    {
        $urls = array();
        $urls[] = Yii::app()->createUrl('homeUCItem/default/getFaxPdf', array('id' => $this->id));
        return $urls;
    }

    public function afterSave()
    {
        if ($this->scenario == 'sendFax') {

            if (!empty($_FILES['UCItem']['tmp_name']['fax_data'])) {
                $file = CUploadedFile::getInstance($this, 'fax_data');

                $this->scenario = '';
                $this->fax_data = null;

                if ($file->tempName != '') {
                    $this->state = FaxDeliveryStatus::Submitted;
                    $this->save();

                    if (!$this->saveFileToFieldByPath("fax_data", $file->tempName)) {
                        $this->state = FaxDeliveryStatus::Failed;
                        $this->save();
                    }
                }
            }
        }
        return parent::afterSave();
    }

    public function beforeDelete()
    {
        if ($this->voicemail_id != null || $this->voicemail_id == '') {
            $voicemail = Voicemail::model()->findByPk($this->voicemail_id);
            if ($voicemail) {
                $voicemail->delete();
            }
        }

        if ($this->typ === UCType::Fax) {
            if (!$this->deleteBinaryField("fax_content_pdf", '', 0)) {
                Log::w('Could not delete file "' . $this->valueForKey('fax_content_pdf') . '.bin"', 'phonalisa-fax');
            }

            if (!$this->deleteBinaryField("fax_data", '', 0)) {
                Log::w('Could not delete file "' . $this->fax_data . '.bin"', 'phonalisa-fax');
            }

            if (!$this->deleteBinaryField("fax_content_tiff", '', 0)) {
                Log::w('Could not delete file "' . $this->valueForKey('fax_content_tiff') . '.bin"', 'phonalisa-fax');
            }
        }
        return parent::beforeDelete();
    }

    public function renderFaxHeader()
    {
        $listData = array();
        $user = app()->user->sudoUserInstance;
        if (!$user) {
            return null;
        }

        if (!empty($user->fax_header_text) && !empty($user->fax_header_number)) {
            $listData[__('UCITEM_RENDER_USER_FAX_HEADER')]['user_' . $user->id] = '<'
                    . $user->fax_header_number
                    . '> '
                    . $user->fax_header_text;
        }

        $group = Groups::model()->findByPk($user->group);
        if (!empty($group->fax_header_text) && !empty($group->fax_header_number)) {
            $listData[__('UCITEM_RENDER_GROUP_FAX_HEADER')]['group_' . $group->id] = '<'
                    . $group->fax_header_number .
                    '> '
                    . $group->fax_header_text;
        }

        $parentGroups = $group->getParentGroups();
        foreach ($parentGroups as $parentGroup) {
            if (!empty($parentGroup->fax_header_text) && !empty($parentGroup->fax_header_number)) {
                $listData[__('UCITEM_RENDER_GROUP_FAX_HEADER')]['group_' . $parentGroup->id] = '<'
                        . $parentGroup->fax_header_number
                        . '> '
                        . $parentGroup->fax_header_text;
            }
        }

        $system = cfg('FAX_HEADER_TEXT');
        $system2 = cfg('FAX_HEADER_NUMBER');
        if (!empty($system) && !empty($system2)) {
            $listData[__('UCITEM_RENDER_SYSTEM_FAX_HEADER')]['system'] = '<' . $system . '> ' . $system2;
        }

        $sortedListData = array();
        foreach ($listData as $key => $value) {
            $sortedListData[$key] = $value;
        }

        return $sortedListData;
    }

    public function getRemoteNumber()
    {
        if ((isset($this->fax_remote_station_id) && $this->fax_remote_station_id != '') && $this->direction == 1) {
            // just on outbound calls!
            return $this->fax_remote_station_id;
        }

        if (isset($this->fax_number) && $this->fax_number != '') {
            return $this->fax_number;
        }

        if (strpos($this->remote_number, 'file-') === 0) {
            return 'file';
        }
        return $this->remote_number;
    }

    public function getDownloadUrl()
    {
        $url = null;

        if ($this->typ == UCType::Fax || $this->typ == UCType::GroupFax) {
            $url = url('homeUCItem/default/getFaxPdf', array('id' => $this->id));
        } elseif ($this->typ == UCType::Callrecording || ($this->typ == UCType::Call && $this->valueForKey('record_data') != '')) {
            $url = url('homeUCItem/default/downloadFile', array('id' => $this->id, 'type' => 'audio/wav'));
        } elseif ($this->voicemail_id != null) {
            $url = url(
                    'homeUCItem/default/downloadFile', array(
                'id' => $this->voicemail_id,
                'type' => 'audio/wav'
                    )
            );
        }
        return $url;
    }

    public function getDirectionIconClass()
    {
        // skip voicemails
        if ($this->voicemail_id != null) {
            return false;
        }
        if ($this->typ == UCType::Callrecording) {
            return false;
        }
        if ($this->state == UCState::Forwarded && $this->typ != UCType::Fax && $this->typ != UCType::GroupFax) {
            return 'icon-share-alt';
        }

        //FIXME my by find a icon wich suits better 
        if ($this->state == UCState::Picked) {
            return 'icon-share-alt';
        }

        switch ($this->direction) {
            case UCDirection::In:
                return 'icon-arrow-down';
            case UCDirection::Out:
                return 'icon-arrow-up';
            default:
                return false;
        }
    }
}
