<?php

class DashboardItem 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'] = isset($htmlOptions['class']) ? $htmlOptions['class'] : $this->ucItemClass;
        $htmlOptions['data-id'] = $this->item->id;

        echo CHtml::tag('div', $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>';
            case UCType::QueueCall:
                return '<i class="icon-sitemap" style="position: relative;top: 12px;"></i>';
            case UCType::Fax:
            case UCType::GroupFax:
                return '<i class="icon-print"></i>';
            case UCType::Call:
                if ($this->item->voicemail_id != null)
                    return '<i class="icon-volume-up"></i>';

                return '<i class="icon-phone"></i>';
            case UCType::Email:
                return '<i class="icon-envelope"></i>';
            case UCType::Callrecording:
                return '<i class="icon-microphone"></i>';
            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 && $this->item->typ != UCType::GroupFax) {
            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>';
            case UCDirection::Out:
                return '<i class="icon-arrow-up direction"></i>';
            default:
                return false;
        }
    }

    private function getSummaryData()
    {
        $content = $this->renderInterlocutor();

        $content .= '<br>';

        if ($this->item->typ == UCType::Fax || $this->item->typ == UCType::GroupFax) {
            $content .= $this->renderFaxTransmissionDetails();
            $content .= '<br>';
        }

        if ($this->item->typ == UCType::GroupCall && $this->item->answered_by != '' || $this->item->typ == UCType::QueueCall && $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);
        }

        $htmlOptions = array();
        $remoteNumberContent = $this->item->getRemoteNumber();

        if ($this->item->getRemoteNumber() == 'file') {
            $remoteNumberContent = __('DASHBORD_ITEM_FORWARDED_TO_FILE') . ': ' . $this->getFileName();
        } 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'] = $remoteNumberContent;
            $htmlOptions['data-ucitem-id'] = $this->item->id;
            $htmlOptions['data-number-type'] = $this->item->typ;
        }
        $remoteNumberContent = urldecode($remoteNumberContent);
        $remoteNumberContent = CHtml::encode($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 = $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->typ != UCType::GroupFax && $this->item->duration != '') {
            $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:
            case UCType::QueueCall:
                return $this->classForCallState();
            case UCType::Fax:
            case UCType::GroupFax:
                return $this->classForFaxState();
            case UCType::Callrecording:
                return 'successCall';
            default:
                return null;
        }
    }

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

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

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

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

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

        if ($this->item->typ == UCType::GroupFax) {
            $model = Groups::model()->findByPk($this->item->owner_id);
            if ($model) {
                $content .= "<p>[" . $model->extension . "]</p>";
            }
        }

        if ($this->item->typ == UCType::QueueCall) {
            $content .= "<p>[" . $this->item->valueForKey('queue_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()
    {
        $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;';
            case FaxDeliveryStatus::Queued:
            case FaxDeliveryStatus::Failed:
                return '<i class="icon-fixed-width icon-refresh icon-spin"></i>&nbsp;';
            case FaxDeliveryStatus::Sent:
                return '<i class="icon-fixed-width icon-ok"></i>&nbsp;';
            case FaxDeliveryStatus::GivingUp:
                return '<i class="icon-fixed-width icon-warning-sign"></i>&nbsp;';
            default:
                return '<i class="icon-fixed-width icon-warning-sign"></i>&nbsp;';
        }
    }

    private function faxDeliveryStateClass()
    {
        if ($this->item->direction == UCDirection::In) {
            switch ($this->item->fax_success) {
                case '1':
                    return 'label-success';
                default :
                    return 'label-important';
            }
        }

        switch ($this->item->state) {
            case FaxDeliveryStatus::Submitted:
                return 'label-inverse';
            case FaxDeliveryStatus::Progress:
            case FaxDeliveryStatus::Queued:
                return 'label-info';
            case FaxDeliveryStatus::Failed:
                return 'label-warning';
            case FaxDeliveryStatus::undefined:
            case FaxDeliveryStatus::GivingUp:
                return 'label-important';
            case FaxDeliveryStatus::Sent:
                return 'label-success';
            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 == UCType::Callrecording || ($this->item->typ == 'call' && $this->item->valueForKey('record_data') != '')) {
            $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 || $this->item->typ == UCType::GroupFax,
            ),
            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->downloadButtonIsVisible(),
            ),
            array(
                'icon' => 'print',
                'label' => '',
                'linkOptions' => array(
                    'data-title' => __('UCITEMS_FAX_INFO'),
                    'rel' => "tooltip"
                ),
                'visible' => $this->item->typ == UCType::Fax || $this->item->typ == UCType::GroupFax,
                '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->item->typ == UCType::GroupFax) {
            $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 downloadButtonIsVisible()
    {
        $hasVoicemailData = !empty($this->item->voicemail_id);
        $hasRecordData = !empty($this->item->valueForKey('record_data'));
        if ($hasVoicemailData || $hasRecordData) {
            return true;
        }

        $downloadableTypes = array(
            UCType::Fax,
            UCType::GroupFax,
            UCType::Callrecording
        );

        if (in_array($this->item->typ, $downloadableTypes)) {
            return true;
        }
        return false;
    }

    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);
    }
}
