<?php

include 'AbstractXmlApp.php';

abstract class AbstractXmlVoicemailApp extends AbstractXMLApp
{

    protected $vmTyp;
    protected $vmID;
    protected $dialVm;
    protected $deleteRequest;
    protected $deleteVm;
    protected static $limit = 20;
    protected $offset;
    protected $page;
    protected $vmTotalCount;
    protected $vmOldCount;
    protected $vmNewCount;
    protected $exit;

    public function run($controller)
    {
        parent::run($controller);
        if ($this->mUser == null) {
            die("not allowed.");
        }
        $this->setAttributes();

        if ($this->exit) {
            return $this->renderExit();
        }

        $this->setVoicemailCounts();

        if ($this->vmTyp && !$this->vmID) {
            return $this->showVoicemails();
        }

        if ($this->vmID && !$this->dialVm && !$this->deleteRequest && !$this->deleteVm) {
            return $this->showVoicemailDetails();
        }

        if ($this->dialVm) {
            return $this->showDialScreen();
        }

        if ($this->deleteRequest) {
            return $this->showDeleteScreen();
        }

        if ($this->deleteVm) {
            return $this->deleteVoicemail();
        }

        $this->renderVoicemailMenu();
    }

    protected function setAttributes()
    {
        $this->vmTyp = @$_REQUEST["vmTyp"];
        $this->vmID = @$_REQUEST["vmID"];
        $this->dialVm = @$_REQUEST["dialVm"];
        $this->deleteRequest = @$_REQUEST["deleteRequest"];
        $this->deleteVm = @$_REQUEST["deleteVm"];
        $this->offset = (int) @$_REQUEST["offset"];
        $this->page = (int) @$_REQUEST["page"];
        $this->exit = @$_REQUEST["exit"];
    }

    protected function setVoicemailCounts()
    {
        $userExtension = $this->mUser->extension;
        $this->vmTotalCount = (int) Voicemail::model()->countByAttributes(array('ownerExtension' => $userExtension));
        $this->vmOldCount = (int) Voicemail::model()->countByAttributes(array('ownerExtension' => $userExtension, 'red' => '1'));
        $this->vmNewCount = (int) Voicemail::model()->countByAttributes(array('ownerExtension' => $userExtension, 'red' => '0'));
    }

    protected function showVoicemails()
    {
        $allVoicemails = $this->getVoicemailsFromCurrentUserByTyp();
        $voicemailType = $this->vmTyp;
        if (count($allVoicemails) === 0) {
            return $this->renderNoEntryFound();
        }
        return $this->renderSelectedVoicemailFolder($allVoicemails, $voicemailType);
    }

    protected function getVoicemailsFromCurrentUserByTyp()
    {
        $voiceMailTyp = $this->vmTyp;
        $read = '0';
        if ($voiceMailTyp === 'old') {
            $read = '1';
        }

        $voicemails = Voicemail::model()->find(array(
            'ownerExtension' => $this->mUser->extension,
            'red' => $read
                ), 'datetime', AbstractXmlVoicemailApp::$limit, $this->offset);
        return $voicemails;
    }

    protected function showVoicemailDetails()
    {
        $voicemail = Voicemail::model()->findByPk($this->vmID);
        return $this->renderVoicemailDetails($voicemail);
    }

    protected function showDialScreen()
    {
        return $this->renderVoicemailRequestMenu('dial');
    }

    protected function showDeleteScreen()
    {
        return $this->renderVoicemailRequestMenu('delete');
    }

    protected function deleteVoicemail()
    {
        $model = UCItem::model()->findByAttributes(array('voicemail_id' => $this->vmID));
        if ($model->delete()) {
            return $this->renderVoicemailDeleted();
        }
    }

    protected function renderVoicemailMenu()
    {
        $this->renderVoicemailStartMenu();
    }

    protected function getVoicemailURI()
    {
        return $this->appURL();
    }

    protected function getVoicemailTypURI()
    {
        return $this->getVoicemailURI() . "?selection=&vmTyp=$this->vmTyp";
    }

    protected function getVoicemailDetailURI()
    {
        return $this->getVoicemailTypURI() . "&vmID=$this->vmID";
    }

    protected function getDialVoicemailURI()
    {
        return $this->getVoicemailDetailURI() . "&dialVm=true";
    }

    protected function getDeleteVoicemailURI()
    {
        return $this->getVoicemailDetailURI() . "&deleteRequest=true";
    }

    protected function getVoicemailOffsetURI()
    {
        return $this->getVoicemailTypURI() . "&offset=$this->offset&page=$this->page";
    }

    protected function getNextVoicemails($currentOffset, $currentPage)
    {
        $this->offset = $currentOffset + AbstractXmlVoicemailApp::$limit;
        $this->page = $currentPage + 1;
        return $this->getVoicemailOffsetURI();
    }

    protected function getPrevVoicemails($currentOffset, $currentPage)
    {
        $this->offset = $currentOffset - AbstractXmlVoicemailApp::$limit;
        $this->page = $currentPage - 1;
        return $this->getVoicemailOffsetURI();
    }

    protected function getVoicemailDateTime($vmID)
    {
        $model = UCItem::model()->findByAttributes(array('voicemail_id' => $vmID));
        return $model->timestamp;
    }

    protected function getUCItemDialToListenNumber($vmID = '')
    {
        if (empty($vmID)) {
            $vmID = $this->vmID;
        }
        $model = UCItem::model()->findByAttributes(array('voicemail_id' => $vmID));
        $voicemail = Voicemail::model()->findByPk($model->voicemail_id);
        if ($voicemail) {
            $voicemail = $this->setVoicemailToken($voicemail);
            return cfg("DP_VOICEMAIL_LISTENING_PREFIX") . "*" . $voicemail->valueForKey('token');
        }
    }

    protected function setVoicemailToken($voicemail)
    {
        if (empty($voicemail->valueForKey('token'))) {
            $token = PasswordGenerator::generatePassword(10, '0123456789');
            $userExtension = $this->mUser->extension;
            if (Voicemail::model()->findByAttributes(array('ownerExtension' => $userExtension, 'token' => $token))) {
                $this->setVoicemailToken($voicemail);
            }
            $voicemail->setValueForKey('token', $token);
            $voicemail->save();
        }
        return $voicemail;
    }

    protected function setVoicemailLanguage()
    {
        $Phone = $this->getPhoneModel();
        $SipAccount = $Phone->getSipAccount();
        $User = $SipAccount->getUser();

        $language = cfg("GUI_LANGS");
        if ($User && $User->user_language != "") {
            $language = $User->user_language;
        }
        Yii::app()->setLanguage($language);
    }

    protected function getNameFromExtension($extension)
    {
        $userAdressbooks = $this->mUser->getAddressbooks();
        $addressbookIDs = array(
            'intern' => array(),
            'privat' => array(),
            'group' => array()
        );
        foreach ($userAdressbooks as $userAdressbook) {
            if ($userAdressbook->type == AddressbookType::intern) {
                $addressbookIDs['intern'][] = $userAdressbook->id;
            }
            if ($userAdressbook->type == AddressbookType::personal) {
                $addressbookIDs['privat'][] = $userAdressbook->id;
            }
            if ($userAdressbook->type == AddressbookType::group) {
                $addressbookIDs['group'][] = $userAdressbook->id;
            }
        }

        $foundNameForExtension = $this->getNameFromAdressbooks($addressbookIDs['intern'], $extension);
        if ($foundNameForExtension != '') {
            return $foundNameForExtension;
        }
        $foundNameForExtension = $this->getNameFromAdressbooks($addressbookIDs['privat'], $extension);
        if ($foundNameForExtension != '') {
            return $foundNameForExtension;
        }
        $foundNameForExtension = $this->getNameFromAdressbooks($addressbookIDs['group'], $extension);
        return $foundNameForExtension;
    }

    protected function getNameFromAdressbooks($addressbookIDs, $extension)
    {
        $foundNameForExtension = '';
        foreach ($addressbookIDs as $addressbookID) {
            $foundNameForExtension = $this->getNameFromAddress($addressbookID, $extension);
        }
        return $foundNameForExtension;
    }

    protected function getNameFromAddress($id, $extension)
    {
        $keysToSearch = array('tel_work', 'tel_cell', 'tel_home', 'tel_cell_private', 'tel_assistent');
        foreach ($keysToSearch as $keyToSearch) {
            $model = Addresses::model()->findByAttributes(array('contact_tid' => $id, $keyToSearch => $extension));
            if ($model != NULL) {
                return $model->getFormatedName();
            }
        }

        return "";
    }

    protected function getTotalPage($vmCount)
    {
        return ceil($vmCount / AbstractXmlVoicemailApp::$limit);
    }
}
