<?php

/**
 * SQL
 * CREATE  TABLE "main"."permissions" (
 *  "id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE ,
 *  "groupId" INTEGER NOT NULL ,
 *  "type" VARCHAR(20) NOT NULL ,
 *  "itemId" INTEGER NOT NULL
 * )
 *
 * This is the model class for table "permissions".
 *
 * The followings are the available columns in table 'permissions':
 * @property integer $id
 * @property integer $groupId
 * @property string $type
 * @property integer $itemId
 */
class Permissions extends PhonalisaRecord
{

    public $id;
    public $groupId;
    public $type;
    public $itemId;

    public static function myAttributes()
    {

        return array(
            'id' => 'id',
            'groupId' => 'groupId',
            'type' => 'type',
            'itemId' => 'itemId',
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Permissions the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'permissions';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('groupId, type, itemId', 'required'),
            #array('groupId, itemId', 'numerical', 'integerOnly'=>true),
            array('groupId, itemId', 'length', 'max' => 255),
            array('type', 'length', 'max' => 30),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, groupId, type, itemId', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'group' => array(self::BELONGS_TO, 'Groups', 'id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => __('ID'),
            'type' => __('Type'),
            'groupId' => __('Group'),
            'itemId' => __('Item'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('groupId', $this->groupId);
        $criteria->compare('type', $this->type, true);
        $criteria->compare('itemId', $this->itemId);

        return new CPhonalisaDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function getItemFromPermission($permission, &$itemName = '')
    {
        $addressbookTypes = array('read', 'write', 'sync', 'csvImport');
        $calendarTypes = array('read_calendar', 'write_calendar', 'sync_calendar');
        $groupTypes = array('sudo', 'intercom', 'pickup', 'monitor', 'eavesdrop', 'statisticGroup');
        $queueTypes = array('statisticQueues', 'monitorQueues', 'advStatisticQueues', "toggleAgentLogin", "moderator");
        $forwardingSetTypes = array('read_forwardingset', 'write_forwardingset');
        $callGroupTypes = array('read');
        if (in_array($permission->type, $addressbookTypes)) {

            $item = Addressbook::model()->findByPk($permission->itemId);
            $itemName = $item ? $item->title : "";
            return $item;
        } elseif (in_array($permission->type, $calendarTypes)) {

            $item = Calendar::model()->findByPk($permission->itemId);
            $itemName = $item ? $item->title : "";
            return $item;
        } elseif (in_array($permission->type, $groupTypes)) {

            $item = Groups::model()->findByPk($permission->itemId);
            $itemName = $item ? $item->name : "";
            return $item;
        } elseif (in_array($permission->type, $queueTypes)) {
            $item = Queue::model()->findByPk($permission->itemId);
            $itemName = $item ? $item->name : "";
            return $item;
        } elseif (in_array($permission->type, $forwardingSetTypes)) {
            $item = ForwardPreset::model()->findByPk($permission->itemId);
            $itemName = $item ? $item->name : "";
            return $item;
        } elseif (in_array($permission->type, $callGroupTypes)) {
            $item = CallGroup::model()->findByPk($permission->itemId);
            $itemName = $item ? $item->name : "";
            return $item;
        } else {
            return;
        }
    }

    public function getPermissionsFromDb()
    {
        $models = array();
        $mregedModels = array();
        $limit = 100;
        $offset = 0;
        do {
            $models = $this->findAll(array(), array('limit' => $limit, 'offset' => $offset));
            $mregedModels = array_merge($mregedModels, $models);
            $offset = $offset + $limit;
        } while (count($models));

        $content = array();
        $sortedContent = array();
        foreach ($mregedModels as $model) {
            $itemName = '';
            $item = $this->getItemFromPermission($model, $itemName);
            if (!$item) {
                $model->delete();
                continue;
            }
            foreach ($model->attributes as $key => $value) {
                $content[$model->id][$key] = $value;
                $content[$model->id]['itemName'] = $itemName;
                $sortedContent[$model->id] = $itemName;
            }
        }
        // sorting content
        asort($sortedContent);
        foreach ($sortedContent as $id => $itemName) {
            $sortedContent[$id] = $content[$id];
        }


        return $sortedContent;
    }

    public function getPermissionsArray($attributes = array(), $recursive = false, $fileName = 'permissions')
    {

        $domain = getPhonalisaDomain();
        $runtimePath = Yii::app()->runtimePath . "/" . $domain . "-" . $fileName . '.ini';
        if (file_exists($runtimePath)) {

            $permissionsArray = parse_ini_file($runtimePath,true);
            
            $permissionVersion = array_shift($permissionsArray);
            $currentDBVersion = DBVersionHelper::getInstance();

            if (!isset($currentDBVersion->version)) {
                $currentDBVersion->version = new DatabaseVersion();
            }


            if (!isset($permissionVersion['dbId'])) {
                $this->createPermissionsFile();
                $permissionsArray = $this->getPermissionsFromDb();
            } elseif (
                $currentDBVersion->version->id != $permissionVersion['dbId'] ||
                $currentDBVersion->version->version != $permissionVersion['version']
            ) {
                $this->createPermissionsFile();
                $permissionsArray = $this->getPermissionsFromDb();
            }
        } else {
            $this->createPermissionsFile();
            $permissionsArray = $this->getPermissionsFromDb();
        }
        if (!count($attributes)) {

            return $permissionsArray;
        } else {
            $result = $this->getSearchResult($attributes, $permissionsArray);
            if ($recursive == true && array_key_exists('groupId', $attributes)) {
                $group = Groups::model()->findByPk($attributes['groupId']);
                while ($group->parent != '0') {
                    $parentGroup = Groups::model()->findByPk($group->parent);
                    $attributes['groupId'] = $parentGroup->id;
                    if (!isset($attributes['type'])) {
                        $result = array_merge($result, $this->getSearchResult($attributes, $permissionsArray));
                    } else {
                        if (count($this->getSearchResult($attributes, $permissionsArray))) {
// 			$result = $this->getSearchResult($attributes,$permissionsArray);
                            $result = array_merge($result, $this->getSearchResult($attributes, $permissionsArray));
                        }
                    }
                    $group = $parentGroup;
                }
            }
        }
        return $result;
    }

    public function getSearchResult($attributes, $permissionsArray)
    {
        $result = array();


        foreach ($attributes as $type => $value) {

            if ($type == 'type' && $value == 'read') {
                $alternativeType = 'write';
            } elseif ($type == 'type' && $value == 'read_calendar') {

                $alternativeType = 'write_calendar';
            } else {
                $alternativeType = null;
            }
        }

        foreach ($permissionsArray as $id => $permissionsAttributes) {
            $addToResult = true;
            foreach ($attributes as $type => $value) {
                if ($addToResult) {
                    $addToResult = $value == $permissionsAttributes[$type] ? true : false;
                    if ($type == 'type' && $alternativeType != null && $addToResult == false) {

                        $addToResult = $alternativeType == $permissionsAttributes[$type] ? true : false;
                    }
                }
            }
            if ($addToResult == true) {
                $result[$id] = $permissionsAttributes;
            }
        }

        return $result;
    }

    public function createPermissionsFile($filePath = 'permissions')
    {
        $domain = getPhonalisaDomain();
        $saveTo = Yii::app()->runtimePath . "/" . $domain . "-" . $filePath . '.ini';

        //Data base version validation :
        $currentDBVersion = DBVersionHelper::getInstance();

        if (!isset($currentDBVersion->version)) {
            $currentDBVersion->version = new DatabaseVersion();
        }

        $currentDBVersion->version->increment();
        $content['version'] = array(
            'version' => $currentDBVersion->version->version,
            'dbId' => $currentDBVersion->version->id
        );


        $content = array_merge($content, $this->getPermissionsFromDb());

        if ($saveTo === null) {
            $saveTo = $this->currentFilePath;
        }
        
        
        PhonalisaIniWriter::writeIniFile($content, $saveTo);
    }

    public function deletePermissionsFile($fileName = 'permissions.ini')
    {
        $domain = getPhonalisaDomain();
        $filePath = Yii::app()->runtimePath . "/" . $domain . "-" . $fileName;
        if (file_exists($filePath)) {
            unlink($filePath);
        }
    }
}
