<?php

/**
model class name  = ExternalHost
form-id  == external-host
*/

class DefaultController extends Controller
{
    /**
    * @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 'index' and 'view' actions
                'actions'=>array('index'),
            	'expression'=>AccessManager::checkSessionPermission($this->module->name),
            		
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
            	'expression'=>AccessManager::checkSessionPermission($this->module->name),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('delete'),
            	'expression'=>AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }


    /**
    * Creates a new model.
    * If creation is successful, the browser will be redirected to the 'view' page.
    */
    public function actionCreate()
    {
        $model = new ExternalHost();
        $this->performAjaxValidation($model);
        if (isset($_POST['ExternalHost'])) {
            $model->attributes = $_POST['ExternalHost'];
            $model->save();
        } 
        $this->renderPartial('_form',array('model'=>$model),false,true);
    }

    /**
    * 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($id) {
        
        $model = $this->loadModel($id);
        $this->performAjaxValidation($model);
        if (isset($_POST['ExternalHost'])) {
            $model->attributes = $_POST['ExternalHost'];
            $model->save();
        } 
        $this->renderPartial('_form',array('model'=>$model),false,true);
    }

    /**
    * Deletes a particular model.
    * If deletion is successful, the browser will be redirected to the 'admin' page.
    * @param integer $id the ID of the model to be deleted
    */
    public function actionDelete($id)
    {
        if(Yii::app()->request->isPostRequest)
        {
//             we only allow deletion via POST request
            $this->loadModel($id)->delete();

//             if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
    * Lists all models.
    */
    public function actionIndex()
    {
        $model = new ExternalHost('search');        
        if(isset($_GET['ExternalHost']))
            $model->attributes = $_GET['ExternalHost'];
        
        $this->render('index',array(
            'model'=>$model,
        ));
    }

    /**
    * 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= ExternalHost::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'] === 'external-host-form') {

            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function renderDropDown($model,$attributeName,$form) {
        $data = $this->getDropDownData($attributeName); 
        $htmlOptions = array(
            'data-translation-target'=>'EXTERNAL_HOST_'.strtoupper($attributeName).'_TARGET',
            'data-translation-id'=>'EXTERNAL_HOST_MODEL_'.strtoupper($attributeName),
            
        );
        return $form->dropDownListRow($model,$attributeName,$data,$htmlOptions);
    }
    
    public function getDropDownData($attributeName) {
        $data = array();
        switch ($attributeName) {
            case 'role':
                $data[ExternalHostTypes::roleForeign] = ExternalHostTypes::getHumanReadableTypeName(ExternalHostTypes::roleForeign);
                $data[ExternalHostTypes::roleMaster] = ExternalHostTypes::getHumanReadableTypeName(ExternalHostTypes::roleMaster);
                //$data[ExternalHostTypes::roleSlave] = ExternalHostTypes::getHumanReadableTypeName(ExternalHostTypes::roleSlave);
            break;         
            case 'type':
                $data[ExternalHostTypes::typeStatic] = ExternalHostTypes::getHumanReadableTypeName(ExternalHostTypes::typeStatic);
                $data[ExternalHostTypes::typeRegisteredInbound] = ExternalHostTypes::getHumanReadableTypeName(ExternalHostTypes::typeRegisteredInbound);
                $data[ExternalHostTypes::typeRegisteredOutbound] = ExternalHostTypes::getHumanReadableTypeName(ExternalHostTypes::typeRegisteredOutbound);
            break;
        }
        return $data;
    }

    public function renderEnum($data,$row,$column) {
        $attributeName = $column->name;
        return ExternalHostTypes::getHumanReadableTypeName($data->$attributeName);
    }
    public function renderBool($data,$row,$column) {
        $attributeName = $column->name;
        if ($attributeName == 'register_state') {
            $this->renderPartial('registerState',array('data'=>$data,'row'=>$row,'column'=>$column));
        } else {
            $html = '';
            if ($data->$attributeName) {
                $html = '<span class="icon-ok" ></span>';
            } else {
                $html = '<span class="icon-remove" ></span>';
            } 
            
            return $html;
        }
    }
    
    public function getTabularFormTabs($form, $model) {
            
            $tabs = array();
            $count = 0;
            $translateKeys = array(
                    'generalData'=>__('EXTERNAL_HOST_TAB_MENU_GENERAL_DATA'),
                    'sipExpertSettings'=>__('EXTERNAL_HOST_TAB_MENU_SIP_EXPERT_SETTINGS'),
            );
            
            foreach ($translateKeys as $view => $tabLabel) {
                $tabs[] = array(
                        'active'=>$count++ === 0,
                        'label'=>$tabLabel,
                        'content'=>$this->renderPartialWithContextHelp($view, array('form'=>$form, 'model'=>$model), true),
                );
            }
            return $tabs;
            
    }
    
    public function getExternalHostGridViewSettings($model, $columns)
    {
        $gridViewSettings = array(
            'id' => 'external-host-grid',
            'headerTitle' => 'Header_title', // optional
            'addButtonTitle' => 'ADD_NEW_EXTERNAL_HOST', // optional
            'modalCreateHeader' => 'EXTERNAL_HOST_HEADER_CREATE', // optional
            'modalUpdateHeader' => 'EXTERNAL_HOST_HEADER_UPDATE', // optional
            'headerAttribute' => 'name',
            'itemsCssClass' => 'plTable items',
            'modalSize' => 'large', // null, 'large', 'small', 'huge'
            'dataProvider' => $model->search(),
            'filter' => $model,
            'selectableRows' => 0,
            'columns' => $columns,
        );
        
        if (!PhonalisaLicenseManager::routingExternalHostEnabled()) {
            $gridViewSettings['headerTitle'] = 'PHONALISA_CONNECT_HEADER_TITLE';
            $gridViewSettings['addButtonTitle'] = 'ADD_NEW_PHONALISA_CONNECTION';
            $gridViewSettings['modalCreateHeader'] = 'PHONALISA_CONNECT_CREATE';
            $gridViewSettings['modalUpdateHeader'] = 'PHONALISA_CONNECT_UPDATE';
        }
        
        return $gridViewSettings;
    }
}
