<?php

class DefaultController extends Controller
{

    const MANUFACTOR_NAME_HTEK = 'Htek';
    const MANUFACTOR_NAME_SNOM = 'Snom';
    const MANUFACTOR_NAME_TIPTEL = 'Tiptel';
    const MANUFACTOR_NAME_TIPTEL30XX = 'Tiptel30xx';

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'download'
                'actions' => array('download'),
                'users' => array('*'),
            ),
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
                //'users'=>array('@'),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                //'users'=>array('@'),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete', 'deleteRingtone'),
                //'users'=>array('@'),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionDownload()
    {

        if (!isset($_REQUEST['id'])) {
            Log::w("Ringtone Download, but no ID given!", 'Ringtone');
            return;
        }

        $explodedID = explode('/', $_REQUEST['id']);

        if (isset($explodedID[1])) {
            $phoneModel = Phones::model()->findByAttributes(array('mac_addr' => $explodedID[0]));
            if (!$phoneModel) {
                Log::w("Ringtone Download, but no phone-model found!", 'Ringtone');
                return;
            }
            $SipAccount = $phoneModel->getSipAccount();
            if (!$SipAccount) {
                Log::w("Ringtone Download, but no sip-account found!", 'Ringtone');
                return;
            }
            $model = Ringtone::model()->findByAttributes(array('userId' => $SipAccount->user_id, 'fileName' => $explodedID[1]));
            if (!$model) {
                Log::w("Ringtone Download, but no ringtone found!", 'Ringtone');
                return;
            }
            $fileName = $model->fileName;
        } else {
            $fileName = $_REQUEST['id'];
            $parts = explode(".", $fileName);
            $id = $parts[0];
            $model = Ringtone::model()->findByPk($id);
        }

        $length = 0;
        $data = "";
        if ($model != null && $model->getBinaryField('data', $data, $length)) {
            $this->renderPartial(
                    '_ringtoneDownload', array(
                "data" => $data,
                "filename" => $fileName,
                "length" => $length
                    )
            );
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate()
    {
        $model = app()->user->sudoUserInstance;
        $ringtones = Ringtone::model()->findAllByAttributes(array('userId' => $model->id));
        if (isset($_POST['User'])) {

            $model->attributes = $_POST['User'];
            if ($model->save()) {
                if (isset($_FILES['Ringtone']) && $_FILES['Ringtone']['name']['data'] != "") {
                    $newRingtone = new Ringtone();
                    $newRingtone->fileName = $_FILES['Ringtone']['name']['data'];
                    $newRingtone->userId = $model->id;
                    if ($this->phoneUsesBinaryAudioFiles()) {
                        $newRingtone->scenario = 'htek';
                    }
                    if (!$newRingtone->save()) {
                        //throw Error !

                        if ($newRingtone->getError('data') != null) {
                            Yii::app()->user->setFlash('error', $newRingtone->getError('data'));
                        } else {
                            throw new CHttpException(404, 'Can not save data.');
                        }
                    }
                }
                if (isset($_REQUEST['UserSettings'])) {
                    $model->updateSettings($_REQUEST['UserSettings']);
                }

                $model->triggerYourPhones();
                $this->redirect(array('index'));
            }
        }
    }

    public function phoneUsesBinaryAudioFiles()
    {
        if ($this->getCurrentPhoneManufactorName() === self::MANUFACTOR_NAME_HTEK) {
            return true;
        }
        if ($this->getCurrentPhoneManufactorName() === self::MANUFACTOR_NAME_TIPTEL30XX) {
            return true;
        }
        return false;
    }

    public function actionDeleteRingtone($id)
    {
        $model = Ringtone::model()->findByPk($id);
        $model->delete();
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $model = app()->user->sudoUserInstance;
        if (!$model) {
            app()->user->logout();
            app()->user->loginRequired();
        }

        $phone = $this->getCurrentPhoneManufactorName();

        $acceptMimetype = 'audio/*';
        if ($phone === self::MANUFACTOR_NAME_HTEK || $phone === self::MANUFACTOR_NAME_TIPTEL30XX) {
            $acceptMimetype .= ',application/macbinary';
        }

        $this->render('phonesettingsTones', array(
            'model' => $model,
            'ringtone' => new Ringtone(),
            'acceptMimetype' => $acceptMimetype
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = User::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'phonesettings-user-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function renderValue($data)
    {
        $model = app()->user->sudoUserInstance;
        if ($data['type'] == 'bool') {
            return CHtml::checkBox(
                            'User[' . $data['key'] . ']', $model->{$data['key']}, array(
                        'name' => '.$value.',
                        'uncheckValue' => '0'
                            )
            );
        } elseif ($data['type'] == 'text') {
            return CHtml::textField('User[' . $data['key'] . ']', $model->{$data['key']});
        } elseif ($data['type'] == 'ringtone') {

            $stdRingtones = array(
                'ringtone-1' => __('BELLCORE') . ' 1',
                'ringtone-2' => __('BELLCORE') . ' 2',
                'ringtone-3' => __('BELLCORE') . ' 3',
                'ringtone-4' => __('BELLCORE') . ' 4',
                'ringtone-5' => __('BELLCORE') . ' 5',
                'ringtone-6' => __('BELLCORE') . ' 6',
                'ringtone-7' => __('BELLCORE') . ' 7',
                'ringtone-8' => __('BELLCORE') . ' 8',
                'ringtone-9' => __('BELLCORE') . ' 9',
                'ringtone-10' => __('BELLCORE') . ' 10',
                'mute' => __('BELLCORE_MUTE'),
            );
            $userRingtones = $this->getRingtoneListData($model->id);
            $availableRingTones = array(__('CHOOSE_BELLCHOR') => array_merge($stdRingtones, $userRingtones));
            return CHtml::dropDownList('User[' . $data['key'] . ']', $model->{$data['key']}, $availableRingTones);
        } elseif ($data['type'] == 'volume') {
            $settingsModel = $model->getSettings();
            $volume = array();
            for ($i = 1; $i <= 10; $i++) {
                $volume[$i] = __('PHONESETTINGS_TONES_VOLUME') . " $i";
            }
            $volumeSettings = array(__('PHONESETTINGS_TONES_CHOOSE_VOLUME') => $volume);
            return CHtml::dropDownList('UserSettings[' . $data['key'] . ']', $settingsModel->{$data['key']}, $volumeSettings);
        }
    }

    protected function getRingtoneListData($userID)
    {
        $privatRingtones = array();
        if (cfg('USER_RINGTONE_UPLOAD')) {
            $privatRingtones = Ringtone::model()->findAllByAttributes(array('userId' => $userID));
        }
        $systemRingtones = Ringtone::model()->findAllByAttributes(array('userId' => RingtoneOwner::SYSTEM));
        $ringtoneData = array_merge($privatRingtones, $systemRingtones);

        foreach ($ringtoneData as $key => $value) {
            if (endsWith($value->fileName, '.bin') && startsWith($value->fileName, 'ring')) {
                unset($ringtoneData[$key]);
                continue;
            }
            if ($value->userId === RingtoneOwner::SYSTEM) {
                $value->userId = __('RINGTONE_TYPE_SYSTEM');
            } else {
                $value->userId = __('RINGTONE_TYPE_PRIVAT');
            }
        }
        return CHtml::listData($ringtoneData, 'id', 'fileName', 'userId');
    }

    public function renderPhonesettingsTones()
    {
        $phone = $this->getCurrentPhoneManufactorName();
        $userSettings = array();
        $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'key_tone', 'KEY_TONE', 'bool');
        $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'ringtone_int', 'RINGTONE_INTERNAL', 'ringtone');
        $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'ringtone_ext', 'RINGTONE_EXTERNAL', 'ringtone');

        if (PhonalisaLicenseManager::routingQueuesMax()) {
            $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'ringtone_queue', 'RINGTONE_QUEUE', 'ringtone');
        }
        $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'ringtone_callgroup', 'RINGTONE_CALL_GROUP', 'ringtone');

        if ($phone === self::MANUFACTOR_NAME_SNOM || startsWith($phone, self::MANUFACTOR_NAME_TIPTEL) || $phone === self::MANUFACTOR_NAME_HTEK) {
            $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'ringVolume', 'RING_VOLUME');
            $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'receiverVolume', 'RECEIVER_VOLUME');
            $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'receiverMicroVolume', 'RECEIVER_MICRO_VOLUME');
            $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'headsetVolume', 'HEADSET_VOLUME');
            $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'headsetMicroVolume', 'HEADSET_MICRO_VOLUME');
            $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'speakerVolume', 'SPEAKER_VOLUME');
            $userSettings = $this->getPhonesettingsTonesArray($userSettings, 'speakerMicroVolume', 'SPEAKER_MICRO_VOLUME');
        }
        return $userSettings;
    }

    protected function getPhonesettingsTonesArray($phonesettings, $key, $tranlsationTag, $type = 'volume', $value = '')
    {
        $phonesettings[] = array(
            'id' => count($phonesettings),
            'key' => $key,
            'short' => $this->getTextCellContent("PHONESETTINGS_USER_MODEL_" . $tranlsationTag . "_SHORT"),
            'value' => $value,
            'descr' => $this->getTextCellContent("PHONESETTINGS_USER_MODEL_" . $tranlsationTag . "_DESCRIPTION"),
            'type' => $type,
        );
        return $phonesettings;
    }

    public function getTextCellContent($translationKey)
    {
        $content = "";
        $content .= "<p data-translation-id='$translationKey'>" . __($translationKey) . "</p>";
        return $content;
    }

    public function phonesettingsTonesSearch()
    {
        $phonesettings = $this->renderPhonesettingsTones();
        $dataProvider = new CArrayDataProvider($phonesettings, array('pagination' => false));

        return $dataProvider;
    }

    protected function getCurrentPhoneManufactorName()
    {
        $phone = $this->getCurrentPhone();
        if ($phone) {
            $phoneManufactor = PhoneModelFactory::getManufactorOfType($phone->type);
            return get_class($phoneManufactor);
        }
    }

    protected function getCurrentPhone()
    {
        $user_id = Yii::app()->user->sudoUser;
        $User = User::model()->findByPk($user_id);

        if ($User == null) {
            return null;
        }

        $SipAccounts = $User->getSipAccounts();

        if (count($SipAccounts) != 0) {
            $SipAccount = $SipAccounts[0];
            $Phone = $SipAccount->getPhone();
            if ($Phone) {
                return $Phone;
            }
        }
        return null;
    }
}
