<?php

require_once(dirname(realpath(__FILE__)) . '/../../../components/callforwarding/class.usercallforward.php');
require_once(dirname(realpath(__FILE__)) . '/../../../components/callforwarding/class.callforwardingfactory.php');

include 'AbstractXmlApp.php';

abstract class AbstractXMLPhoneConfigApp extends AbstractXMLApp
{

    protected $section = null;
    protected $itemToSet = null;
    protected $itemToSave = null;
    protected $editMode = false;
    protected $number = null;
    protected $siemensConfirmValue = null;
    protected $siemensAlert = null;
    protected $exit;

    protected function setAttributes()
    {
        $this->section = @$_REQUEST["section"];
        $this->itemToSet = @$_REQUEST["setItem"];
        $this->itemToSave = @$_REQUEST["saveItem"];
        $this->number = @$_REQUEST["number"];

        $this->siemensAlert = @$_REQUEST["siemensStartAlert"];
        $this->siemensConfirmValue = @$_REQUEST["siemensConfirmValue"];

        $this->exit = @$_REQUEST['exit'];

        if (@$_REQUEST["editMode"] == "1") {
            $this->editMode = true;
        }
    }

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

        $this->setAttributes();
        if ($this->exit != null) {
            return $this->renderExit();
        }

        //FIXME remove this if more sections are available
        $this->section = "forwarding";
        if ($this->section != null) {
            if ($this->section == "forwarding") {
                $this->runSectionForwarding();
            }
        } else {
            $menuEntries = array();
            $menuEntries[] = array("title" => __('XML_CONFIG_APP_CALL_FORWARDING_TITLE'), "url" => "forwarding");
            $menuEntries[] = array("title" => __('Leistungsmerkmale'), "url" => "features");
            $this->renderConfigMenuList($menuEntries);
        }
    }

    private function runSectionForwarding()
    {
        // Set/Edit item?
        Log::d("itemToSet : " . $this->itemToSet, "siemens-confirm");
        if ($this->itemToSet != null) {
            $item = null;
            $user = $this->mUser;
            $models = $user->getForwardingSets();
            foreach ($models as $model) {
                if ($model->id === $this->itemToSet) {
                    $item = $model;
                    break;
                }
            }

            // just print error if item is null
            Log::d("item : " . $item->id, "siemens-confirm");
            if ($item != null) {
                Log::d("editMode : " . $this->editMode, "siemens-confirm");
                if ($this->editMode) { // SET or EDIT -> EDIT!
                    Log::d('editMode', 'siemens-config');
                    // check scope (system, etc)
                    if ($item->type != ForwardPresetType::PrivatePreset) {
                        $this->renderError(__('XML_CONFIG_APP_NOT_EDITABLE_TEXT'), __('XML_CONFIG_APP_SYSTEM_CALL_FORWARDING_ERROR_TEXT'));
                        die();
                    }
                    // check type (only simple are allowed!)
                    if ($item->forwardType != ForwardType::Immediately) {
                        $this->renderError(__('XML_CONFIG_APP_NOT_EDITABLE_TEXT'), __('XML_CONFIG_APP_CUSTOM_FORWARDING_ERROR_TEXT'));
                        die();
                    }

                    $jsonString = base64_decode($item->configs);
                    $jsonObject = json_decode($jsonString);
                    $userFwd = CallForwardingFactory::getUserCallForwardFromJSONRepresentation($jsonObject, $this->mUser);
                    $simpleFwd = $userFwd->getDefinedSimpleCallforward();
                    $target = $simpleFwd->getCallForwardTarget();

                    if ($target->getCallForwardType() == "number") {
                        $number = $target->getProperty("number");
                        $this->renderCallForwardingItemEditTargetNumberScreen($number, $item->id);
                    } else {
                        $this->renderError(__('XML_CONFIG_APP_NOT_EDITABLE_TEXT'), __('XML_CONFIG_APP_DIRECT_TO_VOICEMAIL_CALL_FORWARDING_MESSAGE'));
                    }
                } else if ($this->itemToSave != null) {
                    Log::d("itemToSave  : " . $this->itemToSave, "siemens-confirm");
                    if ($this->number == "") {
                        $this->renderError(__('XML_CONFIG_APP_ERROR_TITLE'),__('XML_CONFIG_APP_EMPTY_TARGET_MESSAGE'));
                    } else {
                        Log::d("saveNumber", "siemens-config");
                        $jsonString = base64_decode($item->configs);
                        $jsonObject = json_decode($jsonString);
                        $userFwd = CallForwardingFactory::getUserCallForwardFromJSONRepresentation($jsonObject, $this->mUser);
                        $simpleFwd = $userFwd->getDefinedSimpleCallforward();
                        $target = $simpleFwd->getCallForwardTarget();
                        $target->setProperty("number", $this->number);
                        $simpleFwd->setCallForwardTarget($target);
                        $userFwd->setDefinedSimpleCallForward($simpleFwd);
                        $jsonString = CallForwardingFactory::getJSONRepresentationOfUserCallForward($userFwd);
                        $item->configs = base64_encode($jsonString);
                        $item->save();

                        $this->renderError(__('XML_CONFIG_APP_SAVED_TITLE'), __('XML_CONFIG_APP_NEW_DESTINATION_TITLE').": $this->number. " . __('XML_CONFIG_APP_NEW_DESTINATION_INFO_MESSAGE'));
                    }
                } else { // set mode
                    Log::d('save user or not ', "siemens-config");
                    Log::d("ConfirmValue" . $this->siemensConfirmValue, "siemens-config");
                    //siemens fix 

                    if ($this->siemensConfirmValue == "use") {
                        $user->callForwardSet = $item->id;
                        Log::d('saveUser', 'siemens-config');
                        if ($user->save() != true) {
                            $item = null;
                        }
                        // set Item and Print item Set Screen, prints ERROR if Item is null
                        $this->renderCallForwardingItemSet($item);
                    } else if ($this->siemensAlert == 'start') {
                        Log::d('!saveUser', 'siemens-config');
                        $this->renderCallForwardingItemSetConfirm($item);
                    } else {
                        $user->callForwardSet = $item->id;
                        Log::d('saveUser', 'siemens-config');
                        if ($user->save() != true) {
                            $item = null;
                        }
                        // set Item and Print item Set Screen, prints ERROR if Item is null
                        $this->renderCallForwardingItemSet($item);
                    }
                }
            } else { // PRINT's Error
                $this->renderError(__('XML_CONFIG_APP_ERROR_TITLE'), __('XML_CONFIG_APP_INTERNAL_ERROR_OCCURRED_MESSAGE'));
            }
        } else { // Print overview if no item is choosen
            $user = $this->mUser;
            $models = $user->getForwardingSets();
            $sorted = array();
            $unsorted = array();
            foreach ($models as $model) {
                $key = $model->getPhoneKeyModel();
                if ($key != null) {
                    $sorted[$key->key] = $model;
                } else {
                    $unsorted[] = $model;
                }
            }

            foreach ($unsorted as $model) {
                $sorted[] = $model;
            }
            ksort($sorted);
            $this->renderCallForwardingsList($sorted, $user->callForwardSet);
        }
    }

    protected function getMainMenuItemURI()
    {
        $URI = $this->appURL();
        return $URI;
    }

    protected function getForwardMenuURI()
    {
        $URI = $this->appURL(array('section' => "forwarding"));
        return $URI;
    }

    public function getExitURL()
    {
        return $this->getForwardMenuURI() . "&exit=1";
    }

    protected function getCallForwardStatusIcons($name)
    {
        $iconUrl = '/img/16x16/xmlIcons/';
        $host = app()->request->getHostInfo();
        return $host . $iconUrl . $name . '.png';
    }

    // renders config Main Menu
    public function renderConfigMenuList($menuentries)
    {
        
    }

    // renders Callforwading List Menu
    public function renderCallForwardingsList($list, $activeID)
    {
        
    }

    // renders that the callforwading item has been set
    public function renderCallForwardingItemSet($item)
    {
        $title = __('XML_CALL_FORWARDING_CHANGES_ACCEPTED_TITLE');
        $text = __('XML_CONFIG_APP_CALL_FORWARDING_ACTIVATED', true, 'messages', array("{name}" => $item->name));
        if ($item == null) {
            $title = __('XML_CONFIG_APP_ERROR_TITLE');
            $text = __('XML_CONFIG_APP_CALL_FORWARDING_COULD_NOT_SET__ERROR_MESSAGE');
        }
        return $this->renderError($title, $text);
    }

    // renders edit mode for callforwarding
    public function renderCallForwardingItemEditTargetNumberScreen($number, $itemId)
    {
        
    }

    public function renderError($title, $text)
    {
        
    }

    public function renderPhoneInput($input)
    {
        
    }

    public function renderExit()
    {
        
    }

    protected function setConfigAppLanguage()
    {
        $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);
    }
}
