<?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',
                    'export',
                    'import',
                    'generatePDF',
                    "test",
                ),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
    
    public function actionTest() {
        $models = SpeedDial::model()->findAll();
        foreach ($models as $model)
        {
            dump($model->attributes);
            
        }
        die("test");
    }
    
    public function actionIndex()
    {   
        if (isset($_POST["SpeedDial"])) {
            $speedDials = $_POST["SpeedDial"];
            $this->updateUserSpeedDials($speedDials);
        } else if (isset($_POST["SpeedDialEmpty"])) {
            //remove outdated list entrys
            $oldModels = SpeedDial::model()->findAllByAttributes(array("owner" => app()->user->sudoUser));
            foreach ($oldModels as $model) {
                if (empty($model->profile_id)) {
                    $model->delete();
                }
            }
        }
        
        $this->render('index', array(
            'dataProvider' => $this->getUserSpeedDialDataProvider(),
            'model' => SpeedDial::model(),
        ));
    }    
    
    private function updateUserSpeedDials($speedDials)
    {
        $oldModels = $this->getUserSpeedDials();
        $this->updateOldListentrys($oldModels, $speedDials);

        //remove outdated list entrys
        foreach ($oldModels as $model) {
            $model->delete();
        }

        $errors = array();
        foreach ($speedDials as $id => $attributes) {
            $model = new SpeedDial("createUserSpeedDial");
            $attributes["owner"] = app()->user->sudoUser;
            $model->attributes = $attributes;
            
            if (!$model->save()) {
                $errors[] = $model->errors;
            }
        }

        if (!empty($errors)) {
            app()->user->setErrorFlashMessage("CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR");
            $this->redirect(url('phonesettingsSpeedDial/default/index'));
        }
    }
    
    private function updateOldListentrys(&$oldModels, &$speedDials) {
        foreach ($oldModels as $key => $model) {
            if (!empty($model->profile_id)) {
                unset($oldModels[$key]);
                unset($speedDials[$model->id]);
                continue;
            }
            if (array_key_exists($model->id, $speedDials)) {
                $model->attributes = $speedDials[$model->id];
                $model->save();
                unset($speedDials[$model->id]);
                unset($oldModels[$key]);
            }
        }
    }
        
    private function getUserSpeedDialDataProvider()
    {
        return new CArrayDataProvider(
            $this->getUserSpeedDials(),
            array(
                'pagination' => false,
                'sort' => array(
                    'defaultOrder' => 'key ASC',
                ),
            )
        );
    }
    
    private function getUserSpeedDials() 
    {        
        $user = User::model()->findByPk(app()->user->sudoUser);
        $models = array();
        if ($user) {
            $userSpeedDials = SpeedDial::model()->findAllByAttributes(array("owner" => $user->id));
            foreach ($userSpeedDials as $userSpeedDial) {
                $models[] = $userSpeedDial;
            }
            $allSpeedDials = array_merge($models, $this->getSpeedDialListEntrys($user));            
        }
        
        if (empty($allSpeedDials)) {
            $allSpeedDials[] = new SpeedDial("createUserSpeedDial");
        }
        return $allSpeedDials;
    }
    
    private function getSpeedDialListEntrys($user) 
    {
        $speedDialListEntrys = array();
        $groups = $user->getUserGroups();
        $speedDialListIds = array();
        foreach ($groups as $group)
        {
            if (!empty($group->speedDialList)) {
                $speedDialListIds[] = $group->speedDialList;
            }
        }
        
        foreach ($speedDialListIds as $listId) {
            $speedDialList = SpeedDialList::model()->findByPk($listId);
            if (!$speedDialList ) {
                continue;
            }
            $speedDials = $speedDialList->getSpeedDials();
            foreach ($speedDials as $speedDial) {
                $speedDialListEntrys[] = $speedDial;
            }
        }
        return $speedDialListEntrys;
    }
    
    public function actionExport()
    {
        $models = $this->getUserSpeedDials();

        $items = array();

        $blacklistedAttributes = $this->getBlacklistedAttributes();

        foreach ($models as $model) {
            $item = array();
            foreach (SpeedDial::myAttributes() as $attribute) {
                if (!in_array($attribute, $blacklistedAttributes)) {
                    $item[$attribute] = $model->$attribute;
                }
            }
            $items[] = $item;
        }

        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename=speedDial.json');
        header('Pragma: no-cache');
        echo json_encode($items);
    }

    public function actionImport()
    {
        $model = new SpeedDial("createUserSpeedDial");
        $file = CUploadedFile::getInstance($model, 'file');
        if (isset($_POST["SpeedDial"])) {
            
            $overwriteKeys = $_POST["SpeedDial"]["overwrite"] === "0" ? false : true;
            
            $this->validateFile($file, $model);
            
            $fileData = file_get_contents($file->tempName);
            $fileEntrys = json_decode($fileData, true);
            usort($fileEntrys, function ($a, $b) {
                return (int)$a["key"] >=  (int)$b["key"];
            });
            
            $userSpeedDials = $this->getUserSpeedDials();
            
            foreach ($fileEntrys as $entry)
            {
                
                if (array_key_exists((int)$entry["key"], $userSpeedDials)) {
                    if ($overwriteKeys) {
                        $existingSpeedDial = $userSpeedDials[$entry["key"]];
                        if (empty($existingSpeedDial->profile_id)) {
                            $speedDial = $this->getParsedJsonModel($entry);
                            $existingSpeedDial->attributes = $speedDial->attributes;
                            if (!$existingSpeedDial->save()) {
                            }
                        }
                    }
                    continue;
                }
                $speedDial = $this->getParsedJsonModel($entry);
                $speedDial->owner = app()->user->sudoUser;
                $speedDial->save();
            }
        }
        $this->renderPartial('import', array("model" => $model), false, true);
    }
    
    private function validateFile($file, &$model)
    {
        if (!$file) {
            $model->addError("file", __('LICENCE_MODEL_REQUIRED_ERROR_MESSAGE'));
            echo json_encode(array('errors' => array("SpeedDial_file" => array(__('CSV_SELECT_FILE_NO_FILE_SELECTED')))));
            Yii::app()->end();
        } else {
            $fileData = file_get_contents($file->tempName);
            if (!$this->validateFileContent($fileData)) {
                $model->addError("file", __('SPEED_DIAL_IMPORT_INVALID_FILE'));
                echo json_encode(array('errors' => array("SpeedDial_file" => array(__('SPEED_DIAL_IMPORT_INVALID_FILE')))));
                Yii::app()->end();
            }
        }
    }

    private function validateFileContent($json)
    {
        $fileEntrys = json_decode($json, true);
        if (!is_array($fileEntrys)) {
            return false;
        }

        foreach ($fileEntrys as $item) {
            if (!$this->validateImportItem($item)) {
                return false;
            }
        }
        return true;
    }
    
    private function validateImportItem($item) {

        $expectedKeys = array("key", "phoneNumber", "description");
        $speedDial = new SpeedDial("createUserSpeedDial");
        $definedKeys = array_keys($this->getUserSpeedDials());

        if (isset($item["key"]) && in_array($item["key"], $definedKeys)) {
            return true; // will be skiped by saving
        }
        
        foreach ($item as $key => $value) {
            if (!in_array($key, $expectedKeys)) {
                continue;
            } else {
                $speedDial->$key = $value;
            }
        }

        return $speedDial->validate();
    }
    
    private function getParsedJsonModel($entry) {
        $model = new SpeedDial("createUserSpeedDial");
        foreach ($entry as $key => $value) {
            if (property_exists($model, $key)) {
                $model->$key = $value;
            }
        }
        $model->owner = app()->user->sudoUser;
        return $model;
    }
    
    private function getBlacklistedAttributes()
    {
        return array('id', 'owner', 'profile_id');
    }
    
    public function actionGeneratePDF()
    {
        $models = $this->getUserSpeedDials();

        $formatedDate = PhonalisaDate::changeRFC2822EnglishToUserLanguage();
        $extension = app()->user->sudoUserInstance->extension;

        $generator = new SpeedDialPDFGenerator();
        $generator->init(
                __("PHONALISA_SPEEDIALLIST"), __("PHONALISA_SPEEDIALLIST_FOR_EXTENSION")
                . " $extension - $formatedDate"
        );
        $generator->generate($models); // outputs the PDF
    }


    public function renderSpeedDialInput($data, $row, $column) {
        $attribute = $column->name;
        if ($data->id) {
            $fieldName = get_class($data) . "[" . $data->id . "][" . $attribute . "]";
        } else {
            $fieldName = get_class($data) . "[" . $row . "][" . $attribute . "]";
        }

        return $this->renderPartial("speedDialInput", array("data" => $data, "attribute" => $attribute, "fieldName" => $fieldName), true, false);
    }
}
