<?php

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',
                    'section',
                    'writeDHCPSettings',
                    'dhcpLeases',
                ),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex()
    {
        $model = NetworkSettings::model();
        $sections = array_keys($model->getConfigItemsArray());
        $firstSectionUrl = $this->createUrl("section", array('section' => $sections[0]));
        $this->redirect($firstSectionUrl);
    }

    public function getTabItems($model)
    {
        $configSectionNames = $model->getConfigSectionHumanReadableName();
        $links = array();

        foreach ($model->getConfigItemsArray() as $name => $configSection) {
            $links[] = array(
                'label' => $configSectionNames[$name],
                'url' => $this->createUrl("section", array("section" => $name)),
                'active' => isset($_REQUEST['section']) && $_REQUEST['section'] == $name,
                'linkOptions' => array(
                    'data-translation-id' => 'NETWORK_ADAPTER_SETTINGS_SECTION_TITLE_' . $name,
                ),
            );
        }

        if ((isset($_REQUEST['section']) && $_REQUEST['section'] == 'DHCP') || !isset($_REQUEST['section'])) {
            $links[] = array(
                'label' => __('NETWORK_ADAPTER_SETTINGS_DHCP_LEASES'),
                'icon' => 'sort-by-order',
                'url' => url('networkDHCP/default/dhcpLeases'),
                'position' => 'right',
                'active' => !isset($_REQUEST['section']) ? true : false,
                'linkOptions' => array(
                    'data-translation-id' => 'NETWORK_ADAPTER_SETTINGS_DHCP_LEASES',
                )
            );
        }
        return $links;
    }

    public function actionSection()
    {
        $model = NetworkSettings::model();
        $action = @Yii::app()->request->getParam("action");
        $section = Yii::app()->request->getParam("section");

        if (isset($action) && $action == 'save') {
            $this->renderIndexAfterSavePostData();
        } else {
            PhonalisaCtrldConnector::hasConnection();
            $this->render('index', array('model' => $model, 'section' => $section));
        }
        Yii::app()->end();
    }

    protected function renderIndexAfterSavePostData()
    {
        if (isset($_POST['NetworkSettings'])) {
            $model = $this->writePostDataToModel();
            if (!NetworkSettings::writeDhcpConfigsToCtrld()) {
                app()->user->getFlash('success'); // removes success-flash-message from model->save()
            }
            $this->render('index', array(
                'model' => $model,
                'section' => Yii::app()->request->getParam("section"))
            );
        }
    }

    protected function writePostDataToModel()
    {
        $networkSettings = $_POST['NetworkSettings'];
        $networkSettings['PROV_HOST'] = NetworkSettings::getValueByKey('PROV_HOST');
        $networkSettings['PROV_PORT'] = NetworkSettings::getValueByKey('PROV_PORT');

        foreach ($networkSettings as $key => $postAttributes) {
            $model = NetworkSettings::model()->findByAttributes(array('key' => $key));
            if ($model == NULL) {
                $model = new NetworkSettings();
            }
            $model->key = $key;
            $model->value = trim($postAttributes);
            $this->saveModel($model);
        }
        return $model;
    }

    protected function saveModel($model)
    {
        if ($model->save()) {
            Yii::app()->user->setSuccessFlashMessage();
        } else {
            Yii::app()->user->setErrorFlashMessage();
        }
    }

    public function actionDhcpLeases()
    {
        $model = NetworkSettings::model();
        $dataProvider = new CArrayDataProvider(array(), array());

        if (PhonalisaCtrldConnector::hasConnection()) {
            $dataProvider = $model->getDHCPLeases();
        }
        $this->render('dhcpLeases', array('model' => $model, 'dataProvider' => $dataProvider));
    }

    public function getHumandReadableDhcpStartTime($data, $key, $value)
    {
        return PhonalisaDate::userDateTime($data[$value->name], true);
    }

    public function renderValue($data)
    {
        return $this->renderPartial('_valueColumn', array('model' => $data), true);
    }
}
