<?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',
                    'create',
                    'update',
                    '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 Blacklist();
        $pattern = new BlacklistPattern();
        $this->performAjaxValidation($model);
        if (isset($_POST['Blacklist'])) {
            $model->attributes = $_POST['Blacklist'];

            if (!$model->save()) {
                log::w();
            } else {
                $this->savePatterns($model->id);
            }
        }
        $this->renderPartial('_form', array(
            'model' => $model,
            'pattern' => $pattern,
            'modelName' => strtoupper(get_class($model)),
            'actionName' => 'create'
                ), 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);
        $pattern = new BlacklistPattern();
        if (isset($_POST['Blacklist'])) {
            $model->attributes = $_POST['Blacklist'];
            if (!$model->save()) {
                log::w();
            } else {
                $this->savePatterns($model->id);
            }
        }
        $this->renderPartial('_form', array(
            'model' => $model,
            'pattern' => $pattern,
            'modelName' => strtoupper(get_class($model))
                ), false, true);
    }

    public function savePatterns($modelId)
    {
        $oldParams = $this->getOldParams($modelId);

        if (isset($_POST['BlacklistPattern'])) {
            $post = $_POST['BlacklistPattern'];
            $postedPatterns = $this->getPostetPatterns($post);

            foreach ($oldParams as $oldParam) {
                $oldParam->delete();
            }

            foreach ($postedPatterns as $post) {
                if (!in_Array($post, $oldParams)) {
                    if ($post != '') {
                        $newpattern = new BlacklistPattern();
                        $newpattern->pattern = $post;
                        $newpattern->blacklistId = $modelId;
                        if (!$newpattern->save()) {
                            
                        }
                    }
                }
            }
        } else {
            foreach ($oldParams as $oldParam) {
                $oldParam->delete();
            }
        }
    }

    public function getPostetPatterns($post)
    {
        $postedPatterns = array();
        foreach ($post as $row => $attributes) {
            $postedPatterns[] = $attributes['pattern'];
        }
        return $postedPatterns;
    }

    public function getOldParams($modelId)
    {
        $oldParams = BlacklistPattern::model()->findAllByAttributes(array('blacklistId' => $modelId));
        return $oldParams;
    }

    /**
     * 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 Blacklist('search');
        if (isset($_GET['Blacklist'])) {
            $model->attributes = $_GET['Blacklist'];
        }

        $this->render('index', array(
            'model' => $model,
            'modelName' => get_class($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 = Blacklist::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'] === 'blacklist-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function renderPatternInput($data, $row, $column)
    {
        $modelName = get_class($data);
        $this->renderPartial('patternInput', array(
            'data' => $data,
            'row' => $row,
            'column' => $column,
            'modelName' => $modelName
        ));
    }

    public function getTabItems($modelName)
    {
        return array(
            array(
                'label' => __('ROUTINGBLACKLIST_NAVBAR_HEADER_TITLE_BLACKLIST'),
                'icon' => 'icon-ban-circle',
                'url' => url('routingBlacklist/default/index'),
                'active' => $modelName == 'Blacklist' ? true : false,
                'linkOptions' => array(
                    'data-translation-id' => 'ROUTINGBLACKLIST_NAVBAR_HEADER_TITLE_BLACKLIST',
                )
            ),
            array(
                'label' => __('ROUTINGBLACKLIST_NAVBAR_HEADER_TITLE_WHITELIST'),
                'icon' => 'icon-circle-blank',
                'url' => url('routingBlacklist/whitelist/index'),
                'active' => $modelName == 'Whitelist' ? true : false,
                'linkOptions' => array(
                    'data-translation-id' => 'ROUTINGBLACKLIST_NAVBAR_HEADER_TITLE_WHITELIST',
                )
            ),
        );
    }
}
