<?php

class AjaxController 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('simpletree', 'load', 'update'),
				//'users'=>array('@'),
				'expression'=>AccessManager::checkSessionPermission($this->module->name),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	
	public function actionUpdate()
        {
	
            $parentId = $this->extractIdFromRequestValue($_REQUEST['parentId']);
            $modelId = $this->extractIdFromRequestValue($_REQUEST['id']);

            $model = $this->loadModel($modelId);
            $model->parent = $parentId; 
            echo json_encode($model->save());
            $model->updateNestedIndex();
	}
        
	private function extractIdFromRequestValue($requestValue) 
        {
            $explodedData = explode('-', $requestValue);
            $lastElement = end($explodedData);
            $id = str_replace('_', '-', $lastElement); 
            return $id;
        }
	
	public function actionLoad()
    {
        Yii::import('application.extensions.treetable.JTreeTable');
        
        $parentId = $_REQUEST['id'];
        
        
        $modelId = str_replace('_', '-', end(explode('-', $parentId)));
        
        $this->widget('ext.treetable.JTreeTable',array(
            'ajaxRequest' => true,
            'primaryColumn'=>'id',
            'parentColumn'=>'parent',
            'sortField' => 'name',
            'columns'=>array(
                'name',
                'extension',
                'description',
                'edit'=>array(
                    'label'=>'test label',
                    'headerHtmlOptions'=>array('width'=>80),
                    'htmlOptions'=>array('align'=>'center'),
                ),
            ),
            'model' => $this->loadModel($modelId),
            'options'=>array(
                'initialState'=>'collapsed',
            ),
        ));
        
        
        //dump($model->find(array('id' => $modelId), 'id'))
        //dump($this->loadModel($modelId));
        //die('xxxx');
        //JTreeTable::renderChildModels($this->loadModel($modelId));
        //JTreeTable::performAjax;
    }
	
	public function actionSimpletree()
    {
        Yii::import('application.extensions.SimpleTreeWidget');
        //sleep(50);    
        SimpleTreeWidget::performAjax();
    }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	

	/**
	 * 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=Groups::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
    
    public function loadGroupModel($group){        
        $model=new Groups('search');        
        
        $criteria = $model->getDbCriteria(true);
        $criteria->addCondition(array('type'=>$group));
        $model->setDbCriteria($criteria);
    
        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']==='groups-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
    
    public function getPermissions($model){
        $dataProvider=new CArrayDataProvider($model->permissions, array(
            'id'=>'id',
            'sort'=>array(
                'attributes'=>array('id'),
            ),
        ));
        return $dataProvider;
    }

    public function getPermissionTypes($groupType){
        $groups = $this->availableGroupTypes();
        return $groups[$groupType]['permissionTypes'];
    }
    
    public function loadPermissionByAttributes($permissionType, $itemId, $groupId){
        return Permissions::model()->findByAttributes(array('type'=>$permissionType,'itemId'=>$itemId,'groupId'=>$groupId));
    }
    
    public function loadPermissionsByItemId($itemId){
        return Permissions::model()->findByAttributes(array('itemId'=>$itemId));
    }
    
    public function loadPermissionsByGroupId($groupId){
        return Permissions::model()->findByAttributes(array('groupId'=>$groupId));
    }
             
}