<?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/column1';

    /**
     * @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()
    {
        $user = app()->user->sudoUserInstance; // FIXME !
        if ($user) {
            $calendarCount = count($user->getCalendars());
        } else {
            $calendarCount = 0;
        }


        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'generateData', 'getJsonEvents', 'hideCalendar'),
                //'users'=>array('@'),
                'expression' => $calendarCount . '!= 0', //AccessManager::checkSessionPermission($this->module->name),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                //'users'=>array('@'),
                'expression' => $calendarCount . '!= 0', //AccessManager::checkSessionPermission($this->module->name),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                //'users'=>array('@'),
                'expression' => $calendarCount . '!= 0', //AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * 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),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.print_r($attributes['start']);die();
     */
    public function actionCreate()
    {
        $model = new CalendarEvent();
        if (isset($_COOKIE['PhonalisaLastUsedCalendarEventType'])) {
            $model->type = $_COOKIE['PhonalisaLastUsedCalendarEventType'];
        }

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['CalendarEvent'])) {

            $model->attributes = $_POST['CalendarEvent'];
            $writePermission = $model->isWriteable();
            $model->convertDateToServerFormat();

            if ($writePermission) {
                if ($model->type == '') {
                    $model->type = $this->saveCustomEventType($model->customType);
                }

                setcookie("PhonalisaLastUsedCalendarEventType", $model->type);
                Log::d('before save()', "calendar-event-debug");
                Log::d($model->start, "calendar-event-debug");

                if (!$model->save()) {
                    print_r($model->errors);
                    die();
                } else {
                    $this->initiateSyncForEachContactList($model->calendar);
                    $model->convertDateToUserFormat();
                    http_response_code(201);
                    header('Content-Type: application/json');
                    echo json_encode($model->formatJsonEventWithColor());
                    Yii::app()->end();
                }
            } else {
                throw new CHttpException(403, 'No permissions to update this resource');
            }
        }
        $availableCalendarTypes = Calendar::model()->getEventTypeList();
        $availableCalendarTypes[''] = __('CALENDEREVENT_MODEL_ADD_NEW_EVENT_TYPE');

        $model->start = PhonalisaDate::convertServerDateTo('c', $model->start, true);
        $model->end = PhonalisaDate::convertServerDateTo('c', $model->end, true);

        $availableCalendars = Calendar::model()->getColoredCalendarList(true);

        $this->renderPartial(
                '_form', array(
            'model' => $model,
            'editable' => true,
            'availableCalendars' => $availableCalendars,
            'availableCalendarTypes' => $availableCalendarTypes,
                ), 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);
        $writePermission = $model->isWriteable();

        $this->performAjaxValidation($model);

        if (isset($_POST['CalendarEvent'])) {

            $oldEventType = $model->type;
            $model->attributes = $_POST['CalendarEvent'];
            $model->convertDateToServerFormat();

            if ($writePermission) {
                if ($model->type == '') {
                    $model->type = $this->saveCustomEventType($model->customType);
                }

                if (!$model->save()) {
                    print_r($model->errors);
                    die();
                } else {
                    $this->initiateSyncForEachContactList($model->calendar);
                    //deleteEventType :
                    if ($oldEventType != $model->type) {
                        $otherModelWithEventType = CalendarEvent::model()->findByAttributes(
                                array('type' => $oldEventType)
                        );
                        if (!$otherModelWithEventType) {
                            $oldEventType = EventType::model()->findByPk($oldEventType);
                            if ($oldEventType) {
                                $oldEventType->delete();
                            }
                        }
                    }

                    //$model->convertDateToUserFormat();
                    $model->start = PhonalisaDate::convertServerDateTo('c', $model->start, true);
                    $model->end = PhonalisaDate::convertServerDateTo('c', $model->end, true);
                    http_response_code(202);
                    header('Content-Type: application/json');
                    echo json_encode($model->formatJsonEventWithColor());
                    Yii::app()->end();
                }
            } else {
                throw new CHttpException(403, 'No permissions to update this resource');
            }
        }

        $availableCalendarTypes = Calendar::model()->getEventTypeList();
        $availableCalendarTypes[''] = __('CALENDEREVENT_MODEL_ADD_NEW_EVENT_TYPE');

        $model->convertDateToUserFormat();
        $this->renderPartial(
                '_form', array(
            'model' => $model,
            'editable' => $model->isWriteable(),
            // display only writable calendars if user can edit
            'availableCalendars' => Calendar::model()->getColoredCalendarList($writePermission),
            'availableCalendarTypes' => $availableCalendarTypes,
                ), false, true
        );
    }

    /**
     * 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
            $model = $this->loadModel($id);

            // check if user has write perissions on current calendar
            if ($model->isWriteable()) {
                header('Content-Type: application/json');
                echo json_encode($model->id);
                $model->delete();
                $this->initiateSyncForEachContactList($model->calendar);
            } else {
                throw new CHttpException(403, 'No permissions to delete this resource');
            }

            Yii::app()->end();

            // 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('admin'));
            }
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    private function initiateSyncForEachContactList($calendarId)
    {
        $iCloudContactList = iCloudContactsList::model()->findAllByAttributes(array('plDirectoryId' => $calendarId));
        if (!empty($iCloudContactList)) {
            foreach ($iCloudContactList as $iCloudContactList) {
                if (isset($iCloudContactList)) {
                    $iCloudContactList->startICloudSync();
                }
            }
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $newEvent = new CalendarEvent();
        if (isset($_POST['CalendarEvent'])) {

            $newEvent = new CalendarEvent();
            $newEvent->attributes = $_POST['CalendarEvent'];
            $newEvent->save();
        }

        $availableCalendars = Calendar::model()->getCalendarList();
        $createNewEventEnabled = count(Calendar::model()->getColoredCalendarList(true));

        if (!isset($_COOKIE['PhonalisaActiveCalendars']) || $_COOKIE['PhonalisaActiveCalendars'] == "") {
            $_COOKIE['PhonalisaActiveCalendars'] = implode(",", array_keys($availableCalendars));
        }

        $this->render(
                'index', array(
            'eventSources' => Calendar::model()->getEventSources(),
            'availableCalendars' => $availableCalendars,
            'addNewEventEnabled' => $createNewEventEnabled,
            'availableCalendarTypes' => Calendar::model()->getEventTypeList(),
                )
        );
    }

    public function actionGetJsonEvents()
    {
        $calendarId = $_GET['id'];

        Yii::app()->user->setState('visibleCalendars[' . $calendarId . ']', true);
        $calendar = Calendar::model()->findByPk($calendarId);
        if ($calendar->type == CalendarType::personal) {
            $models = CalendarEvent::model()->find(
                    array(
                'calendar' => $calendarId,
                'owner' => app()->user->sudoUserInstance->id
                    ), 'start'
            );
        } else {
            $models = CalendarEvent::model()->find(array('calendar' => $calendarId), 'start');
        }

        $events = array();

        foreach ($models as $i => $model) {

            $model->start = PhonalisaDate::convertServerDateTo('c', $model->start, true);
            $model->end = PhonalisaDate::convertServerDateTo('c', $model->end, true);
            $events[] = $model->formatJsonEvent();
        }

        header('Content-Type: application/json');
        echo CJSON::encode($events);
        Yii::app()->end();
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new Calendar('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Calendar'])) {
            $model->attributes = $_GET['Calendar'];
        }
        $this->render('admin', array(
            'model' => $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 = CalendarEvent::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'] === 'calendar-form') {

            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionHideCalendar()
    {
        Yii::app()->user->setState('visibleCalendars[' . $_GET['calendarId'] . ']', false);
    }

    public function saveCustomEventType($customEventType)
    {
        //check If CustomType exsists
        $model = EventType::model()->findByAttributes(array('name' => $customEventType));

        if ($model) {
            return $model->id;
        } else {
            //saveCustomEventType if not exsists
            $newEventType = new EventType();
            $newEventType->name = $customEventType;

            if ($newEventType->save()) {
                //return customType->id
                return $newEventType->id;
            } else {
                //throw Exception
                dump($newEventType->errors);
                die();
            }
        }
    }
}
