<?php

class MobileDashboardItem extends CWidget
{
    public $item;
    public $children = array();
    public $htmlOptions = array();
    public $ucItemClass = 'ucItem';

    private $contentButtons = array();
    private $contentItems = array();
    private $contentMenu = array();

    public function init()
    {
        // this method is called by CController::beginWidget()
    }


    public function run()
    {
        // this method is called by CController::endWidget()
        //FIXME ?
        if ($this->item->typ == 'welcome_email') {
            return;
        }

        $this->renderItem();
    }


    public function addItem($ucItem){
    }


    public function renderItem() {
        
        $content = $this->getTypeCell();
        $content .= $this->getAvatarCell();
        $content .= $this->getSummaryCell();
//        $content .= $this->getContentCell();
//        $content .= $this->getActionsCell();


        $htmlOptions = $this->htmlOptions;
        $htmlOptions['class'] = "ui-btn ui-btn-icon-right ui-icon-carat-r"; 
        $htmlOptions['href'] = url("homeUCItem/default/view", array("id"=> $this->item->id));
       // $htmlOptions['class'] = isset($htmlOptions['class']) ? $htmlOptions['class'] : $this->ucItemClass;
//        $htmlOptions['data-id'] = $this->item->id;
        
        echo CHtml::tag('a', $htmlOptions, $content);
    }


    public function renderChildren(){

    }


    public function renderIcon(){

    }


    private function getIcon(){

    }


    private function renderRating(){
        $content = '';

        $htmlAttributes = array(
            "type" => "radio"
        );

        for($i = 1; $i <= 5; $i++){
            $radioId = 'r' . $i . $this->item->id;

            $htmlAttributes['value'] = $i;
            $htmlAttributes['id'] = $radioId;
            $htmlAttributes['name'] = $this->item->id;
            $htmlAttributes['checked'] = $this->item->rating == $i ? 'checked' : '';

            $content .= CHtml::tag('input', $htmlAttributes, false, true);
            $content .= CHtml::tag('label', array('for' => $radioId), '', true);
            $content .= "\n";
        }

        return CHtml::tag('div', array('class' => 'ucItemRating'), $content);
    }


    private function getTypeIcon(){
        switch ($this->item->typ) {
        case UCType::GroupCall:
            return '<i class="icon-group" style="position: relative;top: 12px;"></i>';
            break;
        case UCType::Fax:
            return '<i class="icon-print"></i>';
            break;
        case UCType::Call:
            if($this->item->voicemail_id != null)
                return '<i class="icon-volume-up"></i>';

            return '<i class="icon-phone"></i>';
            break;
        case UCType::Email:
            return '<i class="icon-envelope"></i>';
            break;
        case UCType::Callrecording:
            return '<i class="icon-microphone"></i>';
            break;

        default:
            return false;
        }
    }

    private function getDirectionIcon(){
        // skip voicemails
        if($this->item->voicemail_id != null)
            return false;
        if($this->item->typ == UCType::Callrecording)
            return false;

        if($this->item->state == UCState::Forwarded && $this->item->typ != UCType::Fax) {
            return '<i class="icon-share-alt direction"></i>';
        }
        
        //FIXME my by find a icon wich suits better 
        if ($this->item->state == UCState::Picked) {
            return '<i class="icon-share-alt direction"></i>';
        }

        switch ($this->item->direction) {
        case UCDirection::In:
            return '<i class="icon-arrow-down direction"></i>';
            break;
        case UCDirection::Out:
            return '<i class="icon-arrow-up direction"></i>';
            break;

        default:
            return false;
        }
    }



    private function getSummaryData() {
    
        $content = $this->renderInterlocutor();
    
        $content .= '<br>';
        
        if($this->item->typ == UCType::Fax){
            $content .= $this->renderFaxTransmissionDetails();
            $content .= '<br>';            
        }        
        
        if ($this->item->typ == UCType::GroupCall && $this->item->answered_by != '') {
            $content .= $this->renderAnsweredByRow();
            $content .= '<br>';
        }
        
        $content .= $this->renderTime();
        return $content;
    }

    private function getFileName() {

        if (strpos($this->item->remote_number,'file-') === 0 ) {
            $fileId = str_replace('file-','',$this->item->remote_number);
            $file = AudioFile::model()->findByPk($fileId);
            if ($file) {
                return $file->name;
            } else {
                return "???";
            }
        } else {
            return "???";
        }
    }

    private function remoteIsCallable(){
        //         if(isset($this->item->remote_number))
        //             return true;
        if($this->item->getRemoteNumber()) {
            return true;
        }
        return false;
    }


    private function renderInterlocutor() {
    
        $name = $this->item->getInterlocutorName();    
        $content = '';
        

        if ($name) {
            $content = '<i class="icon-fixed-width icon-user"></i>&nbsp;' . CHtml::encode($name);
        }
        
        #$content .= '<br><i class="icon-phone"></i>&nbsp;' . CHtml::tag('span', $htmlOptions, ' [&nbsp;'.$this->item->remote_number.'&nbsp;]');

        /*
        $content .= CHtml::link(
                            $name,
                            '',
                            array(
                                'data-title'=> '<i class="icon-user"></i> ' . $name,
                                //'data-trigger'=>'hover',
                                'data-content'=>'
                                    <i class="icon-phone"></i> <a href="#">Call user ('.$this->item->remote_number.')</a><br />
                                    <i class="icon-comments"></i> <a href="#">Jabber message</a><br />
                                    <i class="icon-envelope"></i> <a href="#">New mail</a><br />',
                                'rel'=>'popover',
                            )
                        );
        */

        $htmlOptions = array();

        if ( $this->item->getRemoteNumber()  == 'file') {
            $remoteNumberContent = __('DASHBORD_ITEM_FORWARDED_TO_FILE').': '.$this->getFileName();
        } else {
            $remoteNumberContent = $this->item->getRemoteNumber();
            if ($this->item->typ == 'fax') {
                $htmlOptions['class'] = $this->remoteIsCallable() ? 'sendFax' : '';
            } else {
                $htmlOptions['class'] = $this->remoteIsCallable() ? 'callable' : '';
            }
            if ($this->item->caller_addressbook_id != '' || $this->item->caller_addressbook_id != null) {
                $htmlOptions['data-address-reference'] = $this->item->caller_addressbook_id;
            }
            $htmlOptions['data-phone-number'] = $this->item->remote_number;
            $htmlOptions['data-ucitem-id'] = $this->item->id;
        }

        $remoteNumberContent = urldecode($remoteNumberContent);
        if ($remoteNumberContent) {
            $content .= '<br>' . $this->summaryTypeIcon() . CHtml::tag('span', $htmlOptions, ' [&nbsp;'.$remoteNumberContent.'&nbsp;]');
        }
        $state = $this->item->state;
        if($state == UCState::Forwarded || $state == UCState::Picked) {
        
            $class = '';
            
            if ($this->item->target != '' ||  $this->item->picked_by != '') {
            
                $pos = strpos($this->item->target,'file-');
                if ($pos === 0) {
                    $fileId = str_replace('file-','',$this->item->target);
                    $file = AudioFile::model()->findByPk($fileId);
                    if ($file != NULL) {
                        $fileName =  $file->name;
                        $this->item->target = __('DASHBORD_ITEM_FORWARDED_TO_FILE').': '.$fileName;
                    } else {
                        $this->item->target = "???";
                    }
                    $class = '';
                }

                $pos = strpos($this->item->target,'vm-');
                if($pos === false ) {
                    $targetNumber = $this->item->target;
                    if (!$targetNumber) {
                        $targetNumber = $this->item->picked_by;
                    } 
                    $htmlOptions = array();
                    $htmlOptions['class'] = $class;
                    if ($targetNumber != '') {
                        $htmlOptions['data-phone-number'] =  $targetNumber;
                    } 
                    $htmlOptions['data-ucitem-id'] = $this->item->id;
                    
                    $content .= '<br>' . $this->summaryTargetIcon() . CHtml::tag('span', $htmlOptions, ' [&nbsp;'.$targetNumber.'&nbsp;]');
                }
            }
        }

        return $content;
    }


    private function summaryTypeIcon(){
        if($this->item->typ == 'fax'){
            return '<i class="icon-fixed-width icon-print"></i>';
        } else {
            return '<i class="icon-fixed-width icon-phone"></i>';
        }
    }


    private function summaryTargetIcon(){
        if($this->item->state == UCState::Forwarded){
            return '<i class="icon-fixed-width icon-share-alt"></i>';
        } elseif($this->item->state == UCState::Picked) {
            return '<i class="icon-fixed-width icon-external-link"></i>';
        }
    }


    private function renderTime(){

//         $timestamp = getUserDateTime($this->item->timestamp);
        $timestamp = $this->item->timestamp;
        $content = '<i class="icon-fixed-width icon-calendar"></i>&nbsp;';

        $content .= '<span>'.PhonalisaDate::userDateTime($timestamp).'</span>';
        
        if($this->item->typ != UCType::Fax && $this->item->duration != ''){
            $content .= '<br>';
            $duration = RelativeDateFormatter::durationInNumbers($this->item->duration);
            $content .= '<span class="duration">&nbsp;<i class="icon-fixed-width icon-time"></i>'.$duration.'</span>';
        }

        return $content;
    }
    
    
    // depricated
    private function renderDuration(){
        $duration = RelativeDateFormatter::durationInNumbers($this->item->duration);
        
        $content = '<i class="icon-fixed-width icon-time"></i>&nbsp;';
        $content .= '<span>'.$duration.'</span>';
        
        if($this->item->typ == 'fax')
            $content = $this->renderFaxTransmissionDetails();

        return $content;
    }
    
    


    private function getStateClass() {
        switch ($this->item->typ) {
            case UCType::Call:
            case UCType::GroupCall:
                return $this->classForCallState();
                break;
            case UCType::Fax:
                return $this->classForFaxState();
                break;
            case UCType::Callrecording:
                return 'successCall';
                break;
            default:
                return null;
        }
    }


    private function classForCallState() {

        switch ($this->item->state) {
            case UCState::Ringing:
            case UCState::Answered:
                return 'activeCall';
                break;
            case UCState::Forwarded:
                return 'forwardedCall';
                break;
            case UCState::Picked:
                return 'pickedCall';
                break;
            case UCState::Blindtransfered:
            case UCState::Attendedtransfered:
            case UCState::Missed:
                return 'missedCall';
                break;
            case UCState::Success:
                return 'successCall';
                break;
            default:
                return '';
        }
    }


    private function classForFaxState(){

        if ($this->item->direction == UCDirection::In) {
            switch ($this->item->fax_success) {
            case '1':
                return 'successCall';
                break;
            default :
                return 'missedCall';
            }
        }

        switch ($this->item->state) {
        case FaxDeliveryStatus::Submitted:
        case FaxDeliveryStatus::Progress:
        case FaxDeliveryStatus::Queued:
            return 'activeCall';
            break;
        case FaxDeliveryStatus::Failed:
            return 'missedCall';
            break;
        case FaxDeliveryStatus::undefined:
        case FaxDeliveryStatus::GivingUp:
            return 'missedCall';
            break;
        case FaxDeliveryStatus::Sent:
            return 'successCall';
            break;
        default:
            return '';
        }
    }


    private function getTypeCell() {
        $content = $this->getDirectionIcon();
        $content .= $this->getTypeIcon();

        if ($this->item->typ == UCType::GroupCall) {
            $content.= "<p>[".$this->item->group_extension."]</p>";
        }

        $stateClass = $this->getStateClass();

        return CHtml::tag('div', array('class' => 'ucType ' . $stateClass), $content);
    }


    private function renderDeleteButton() {
        return CHtml::link(
            '<i class="icon-trash"></i>',
            array(
                'delete',
                'id'=>$this->item->id,
                'ajax'=>'homeUCItem',
            ),
            array(
                'class'=> 'delete',
                'rel' => 'tooltip',
                'id' => $this->item->id,
                'data-original-title' => __('UCITEMS_DELETE_TOOLTIP'),
            )
        );
    }


    private function renderVoiceMail(){
        $voicemailUrls = $this->item->getVoicemailUrls();
        $player = $this->render('audioPlayer', array('urls' => $voicemailUrls, 'item' => $this->item), true);
        return CHtml::tag('div', array(), $player);
    }


    private function getDownoadButton() {
        //  $urls = $this->item->getVoicemailUrls();
        $targetId = isset($this->item->voicemail_id) ? $this->item->voicemail_id : $this->item->id;
        $url = Yii::app()->createUrl('homeUCItem/default/downloadFile', array('id' => $targetId, 'type' => 'audio/wav'));


        return CHtml::tag(
            'a',
            array(
                'href' => $url,
                'class' => "icon-arrow-down icon-fixed-width",
                'style' => $this->item->note != '' ? '' : "display:none",
                'data-title' => __('UCITEMS_DOWNLOAD_FILE_TOOLTIP'),
                'rel' => "tooltip"
            ),
            ''
        );
    }


    private function renderFax(){
        $content = '';

        $faxUrls = array();
        if($this->item->fax_document_total_pages != null){
            $faxUrls = $this->item->getFaxUrls();
        }

        $faxInfo = array(
            'image_pixel_size' => $this->item->fax_image_pixel_size,
            'document_total_pages' => $this->item->fax_document_total_pages,
            'document_transferred_pages' => $this->item->fax_document_transferred_pages,
            'transfer_rate' => $this->item->fax_transfer_rate,
            'image_size' => $this->item->fax_image_size,
            'fax_result_code' => $this->item->fax_result_code,
            'fax_result_text' => $this->item->fax_result_text,
            'tries' => $this->item->tries,
        );


        return $this->render('faxSummary', array('faxUrls' => $faxUrls, 'item' => $this->item, 'faxInfo' => $faxInfo), true);
    }


    private function getAvatarCell() {
        if ($this->item->typ != UCType::Callrecording) {

            $content = CHtml::image($this->item->getAvatarUrl(80), '', array("width" => 50, "height" => 50));
            return CHtml::tag('div', array('class' => 'ucAvatar'), $content);
        } else {
            return CHtml::tag('div', array('class' => 'ucAvatar'), '');
        }
    }


    private function getSummaryCell(){
        return CHtml::tag('div', array('class' => 'ucSummary'), $this->getSummaryData());
    }


    private function renderAnsweredByRow(){
        $content = '<i class="icon-fixed-width icon-share"></i>&nbsp;';
        
        
        $htmlOptions = array();
        $htmlOptions['class'] = 'callable';
        $htmlOptions['data-phone-number'] = $this->item->answered_by;
        $htmlOptions['data-ucitem-id'] = $this->item->id;
       
        $content .= CHtml::tag('span', $htmlOptions, '[&nbsp;'.$this->item->answered_by.'&nbsp;]');

        
        return $content;
    }


    private function renderFaxTransmissionDetails(){
        $content = $this->faxDeliveryStateIcon();
        
        if ($this->item->direction == UCDirection::Out) {
            $text = FaxDeliveryStatus::translate($this->item->state) ;
        } else {
            if ($this->item->fax_success == '1' ) {
                $text = __('FAX_INBOUND_SUCCESS');
            } else {
                $text = __('FAX_INBOUND_FAIL');
            }
        }
                
        $content .= '<span>'.$text.'</span>';
        return $content;
    }


    private function faxDeliveryStateIcon(){      
        switch ($this->item->state) {
            case FaxDeliveryStatus::Submitted:
            case FaxDeliveryStatus::Progress:
                return '<i class="icon-fixed-width icon-spinner icon-spin"></i>&nbsp;';
                break;
            case FaxDeliveryStatus::Queued:
            case FaxDeliveryStatus::Failed:
                return '<i class="icon-fixed-width icon-refresh icon-spin"></i>&nbsp;';
                break;
            case FaxDeliveryStatus::Sent:
                return '<i class="icon-fixed-width icon-ok"></i>&nbsp;';
                break;
            case FaxDeliveryStatus::GivingUp:
                return '<i class="icon-fixed-width icon-warning-sign"></i>&nbsp;';
                break;
            default:
                return '<i class="icon-fixed-width icon-warning-sign"></i>&nbsp;';
                return '';
        }
    }


    private function faxDeliveryStateClass() {

        if ($this->item->direction == UCDirection::In) {
            switch ($this->item->fax_success) {
            case '1':
                return 'label-success';
                break;
            default :
                return 'label-important';
            }
        }
        
        switch ($this->item->state) {
            case FaxDeliveryStatus::Submitted:
                return 'label-inverse';
            case FaxDeliveryStatus::Progress:
            case FaxDeliveryStatus::Queued:
                return 'label-info';
                break;
            case FaxDeliveryStatus::Failed:
                return 'label-warning';
                break;
            case FaxDeliveryStatus::undefined:
            case FaxDeliveryStatus::GivingUp:
                return 'label-important';
                break;
            case FaxDeliveryStatus::Sent:
                return 'label-success';
                break;
            default:
                return '';
        }
    }


    private function getContentCell(){
        $menuItems = $this->setupContentMenu();

        $menu = $this->widget('bootstrap.widgets.TbMenu', array(
            'items' => $menuItems,
            'encodeLabel' => false,
            'htmlOptions' => array(
                'class' => 'nav-dm'
            ),
            'submenuHtmlOptions' => array(
                //'class' => 'dropdown-menu',
            )
        ), true);



        if($this->item->voicemail_id != null  || $this->item->typ == 'callrecording'){
            $this->contentItems[] = $this->renderVoiceMail();
        }

        $content = $this->renderContentItems();
        $note = $this->getNoteForm();


        return CHtml::tag('div', array('class' => 'ucContent'), $menu . $content . $note);//$buttons . $content .
    }

    private function renderContentButtons(){
        $html = '';
        foreach($this->contentButtons as $button){
            $html .= $button;
        }
        return CHtml::tag('div', array(), $html);
    }

    private function renderContentItems(){
        $html = '';
        foreach($this->contentItems as $item){
            $html .= $item;
        }

        if($html != ''){
            CHtml::tag('div', array(), $html);
        }

        return $html;
    }



    private function setupContentMenu(){
        return array(
            array(
                'label' => '',
                'icon' => 'star',
                //'label' => '<span class="badge badge-important">NEW</span>',
                //'class' => 'pull-right',
                'itemOptions'=>array(
                    'class' => 'new-dashboard-item',
                ),
                'linkOptions'=>array(
                    'class' => 'editNote',
                    'data-title' => __('UCITEM_NEW_ICON'),
                    'rel' => "tooltip"
                ),
                'url' => '',
                'visible' => $this->item->red == '0',
            ),
            array(
                'icon' => 'pencil',
                'label' => '',
                'url' => '',

                'linkOptions'=>array(
                    'class' => 'editNote',
                    //'onclick' => "editNote(event);",
                    'data-title' => __('UCITEMS_UPDATE_NOTE'),
                    'rel' => "tooltip"
                ),
            ),
            array(
                'icon' => 'trash',
                'label' => '',
                'url' => '',
                'linkOptions'=>array(
                    'class' => 'removeNote',
                    'data-title' => __('UCITEMS_REMOVE_NOTE'),
                    'rel' => "tooltip",
                    'style' => $this->item->note == '' ? 'display:none' : '',
                ),
            ),
            array(
                'icon' => 'eye-open',
                'label' => '',
                'linkOptions'=>array(
                    "target"=>"_blank",
                    'data-title' => __('UCITEMS_PREVIEW'),
                    'rel' => "tooltip"
                ),
                'url' => url('homeUCItem/default/getFaxPdf', array('id' => $this->item->id)).'&view',
                'visible' => $this->item->typ == UCType::Fax,
            ),
            array(
                'icon' => 'download',
                'label' => '',
                'linkOptions'=>array(
                    'data-title' => __('UCITEMS_DOWNLOAD'),
                    'rel' => "tooltip"
                ),
                //'url' => url('homeUCItem/default/getFaxPdf', array('id' => $this->item->id)),
                'url' => $this->item->getDownloadUrl(),
                'visible' => $this->item->typ == UCType::Fax || $this->item->typ == UCType::Callrecording || $this->item->voicemail_id != null,
            ),
            array(
                'icon' => 'print',
                'label' => '',
                'linkOptions'=>array(
                    'data-title' => __('UCITEMS_FAX_INFO'),
                    'rel' => "tooltip"
                ),
                'visible' => $this->item->typ == UCType::Fax,
                'items' => array(
                    array(
                        'icon' => 'exclamation',
                        'visible' => $this->item->fax_result_text != 'OK' && $this->item->fax_result_text != '',
                        'label' => $this->item->fax_result_text
                    ),
                    array(
                        'icon' => 'resize-full',
                        'label' => $this->item->fax_transfer_rate,
                        'visible' => $this->item->fax_transfer_rate != null
                    ),
                    array(
                        'icon' => 'file-alt',
                        'label' => $this->item->fax_document_transferred_pages . '/' . $this->item->fax_document_total_pages,
                        'visible' => $this->item->fax_document_transferred_pages != null
                    ),
                    array(
                        'icon' => 'dashboard',
                        'label' => $this->item->fax_transfer_rate,
                        'visible' => $this->item->fax_transfer_rate != null
                    ),
                    array(
                        'icon' => 'repeat',
                        'label' => $this->item->tries,
                        'visible' => $this->item->tries != null && $this->item->tries != '1'
                    ),
                )
            ),            
        );


        $this->contentButtons[] = CHtml::tag(
            'a',
            array(
                'class' => "icon-pencil icon-fixed-width",
                'onclick' => "editNote(event);",
                'data-title' => __('GLOBAL_UPDATE_BUTTON'),
                'rel' => "tooltip"
            ),
            ''
        );

        $this->contentButtons[] = CHtml::tag(
            'a',
            array(
                'class' => "icon-trash icon-fixed-width",
                'onclick' => "deleteNote(event);",
                'style' => $this->item->note != '' ? '' : "display:none",
                'data-title' => __('GLOBAL_DELETE_BUTTON'),
                'rel' => "tooltip"
            ),
            ''
        );

        if($this->item->typ == UCType::Fax){
            $this->contentButtons[] = CHtml::tag(
                'a',
                array(
                    'class' => "icon-eye-open icon-fixed-width",
                    'style' => $this->item->note != '' ? '' : "display:none",
                    'data-title' => __('GLOBAL_DELETE_BUTTON'),
                    'rel' => "tooltip"
                ),
                ''
            );

            $this->contentButtons[] = CHtml::tag(
                'a',
                array(
                    'class' => "icon-save icon-fixed-width",
                    'style' => $this->item->note != '' ? '' : "display:none",
                    'data-title' => __('GLOBAL_DELETE_BUTTON'),
                    'rel' => "tooltip"
                ),
                ''
            );         
        }
    }


    private function getNoteForm(){
        return CHtml::tag('div', array('class' => 'ucNote'), $this->item->note);
    }


    public function getActionsCell(){
        $content = $this->renderDeleteButton();
        $content .= $this->renderRating();
        return CHtml::tag('div', array('class' => 'ucActions'), $content);
    }


}


?>