<?php

class WhitelistController extends DefaultController
{
    /**
     * @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('*'),
            ),
        );
    }
    
    public function actionIndex()
    {
        $model = new Whitelist('search');
        if (isset($_GET['Whitelist'])) {
            $model->attributes = $_GET['Whitelist'];
        }

        $this->render('index', array(
            'model' => $model,
            'modelName' => get_class($model)
        ));
    }

    public function actionCreate()
    {
        $model = new Whitelist();
        $pattern = new BlacklistPattern();
        $this->performAjaxValidation($model);

        if (isset($_POST['Whitelist'])) {
            
            $model->attributes = $_POST['Whitelist'];

            if ($model->save()) {
                $this->savePatterns($model->id);
            }
        }
        
        $this->renderPartial('application.modules.routingBlacklist.views.default._form', array(
            'model' => $model,
            'pattern' => $pattern,
            'modelName' => strtoupper(get_class($model)),
            'actionName' => 'create'
                ), false, true);
    }
    
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);
        $this->performAjaxValidation($model);
        $pattern = new BlacklistPattern();
        if (isset($_POST['Whitelist'])) {
            $model->attributes = $_POST['Whitelist'];
            if ($model->save()) {
                $this->savePatterns($model->id);
            }
        }
        $this->renderPartial('application.modules.routingBlacklist.views.default._form', array(
            'model' => $model,
            'pattern' => $pattern,
            'modelName' => strtoupper(get_class($model))
                ), false, true);
    }
    
    public function savePatterns($modelId)
    {
        $oldParams = BlacklistPattern::model()->findAllByAttributes(array('blacklistId' => $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 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.');
        }
    }
    
    /**
     * 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 = Whitelist::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }
    
    public function renderPatternInput($data, $row, $column)
    {
        $modelName = get_class($data);
        $this->renderPartial('application.modules.routingBlacklist.views.default.patternInput', array(
            'data' => $data,
            'row' => $row,
            'column' => $column,
            'modelName' => $modelName
        ));
    }
}
