<?php

class ServiceController extends Controller {

    public function canEdit() {
        return self::canEditStatic();
    }

    public static function canEditStatic() {
        return user()->checkAccessAtLeastOne('verify_all_events', 'check_events', 'verify_suspended_events', 'verify_checked_events', 'confirm_all_events', 'can_set_service_ready_to_evaluate', 'release-services-master');
    }

    public function actionIndex() {
        if (count($_REQUEST) == 0) {
            $scope = 'validable';
        }else{
            $scope = 'valid';
        }
        if (isset($_REQUEST ['allServices'])) {
            $scope = 'valid';
        }
        $crit = array(
            'order' => 'start_time DESC',
            'scopes' => array(
                $scope
            ),
            'with' => array(
                'eventsCount',
                'eventsNewCount',
                'eventsExaminedCount',
                'eventsPendingCount',
                'eventsValidatedCount',
                'eventsQueuedForExportCount',
                'eventsExportedCount',
                'eventsVoidCount'
            )
        );

        $idUser = Yii::app()->user->id;

        if (isset($_REQUEST ['onlyWithEvents'])) {
            $crit ['condition'] = '(SELECT count(*) FROM storicotable onlyWithEvents WHERE onlyWithEvents.id_run=t.id)>0';
        } else if (isset($_REQUEST ['tobevalidated'])) {
            $crit ['condition'] = 'id_user_validating <= 0 AND report_user <= 0 AND (SELECT count(*) FROM storicotable onlyWithEvents WHERE onlyWithEvents.id_run=t.id)>0';
        } else if (isset($_REQUEST ['validating'])) {
            $crit ['condition'] = "id_user_validating = $idUser";
        } else if (isset($_REQUEST ['validating_all'])) {
            $crit ['condition'] = "id_user_validating > 0";
        } else if (isset($_REQUEST ['mine'])) {
            $crit ['condition'] = "in_charge_to = $idUser";
        } else if (isset($_REQUEST ['exported_all'])) {
            $crit ['condition'] = "report_user > 0";
        } else if (isset($_REQUEST ['exported'])) {
            $crit ['condition'] = "report_user = $idUser";
        }

        $dataProvider = new CActiveDataProvider('Service', array(
            'criteria' => $crit,
            'pagination' => array(
                'pageSize' => paramdeep('service', 'paginationSize')
            )
                ));

        $this->render('index', array(
            'dataProvider' => $dataProvider
        ));
    }

    public function actionSummary() {
        $user = Yii::app()->user->model;
        $this->renderPartial("_servicesSummary", array(
            'user' => $user
        ));
    }

    public function filters() {
        return array(
            'postOnly + takeCharge, ReleaseAllPerUser',
            array(
                'application.filters.SyslogFilter - summary'
            )
        );
    }

    public function actionView($id) {
        $this->render('view', array(
            'service' => $this->loadModel($id)
        ));
    }

    /**
     *
     * @param mixed $id          
     * @throws CHttpException
     * @return Service
     */
    public function loadModel($id) {
        return Service::findById($id);
    }

    public function actionStop($id) {
        $service = $this->loadModel($id);
        $operator = Yii::app()->user->model;

        $service->setStop($operator);

        if (!$service->save())
            throw new CHttpException(500, Yii::t('app', 'Cannot save task'));
        Yii::app()->end();
    }

    public function actionStartPlanned($id) {
        $service = $this->loadModel($id);
        $service->setStart();

        if (!$service->save())
            throw new CHttpException(500, Yii::t('app', 'Cannot save service'));
        Yii::app()->end();
    }

    public function actionStartManualConfirm($gateGroupId) {
        $gateGroup = $this->findModel('GateGroup', $gateGroupId);
        $this->renderPartial('/dashboard/service/_create_confirm', array(
            'gateGroup' => $gateGroup
        ));
    }

    public function actionResetValidations($id) {
        $service = $this->loadModel($id);

        foreach ($service->events as $ev) {
            $ev->resetValidation();
        }

        $service->id_user_validating = 0;

        $service->save();

        $this->renderPartial('_serviceRow', array(
            'service' => $service
        ));
    }

    public function actionSetReadyToEvaluate($id) {
        $service = $this->loadModel($id);
        $service->setReadyToEvaluate();
        $this->renderPartial('_serviceRow', array(
            'service' => $service
        ));
    }

    public function actionStartManual() {
        $currentTime = new DateTime ();
        $expectedEndTime = new DateTime('2035-12-31 23:59:59');

        if (isset($_POST ['stopTime']) && $_POST ['stopTime'] != - 1)
            $expectedEndTime->setTimestamp($_POST ['stopTime']);

        $operator = Yii::app()->user->model;

        $gateGroupId = (int) $_POST ['gateGroupId'];

        $service = new Service ();
        $service->setManualStart($currentTime, $expectedEndTime, $gateGroupId, $operator);
        if (!$service->save())
            throw new CHttpException(500, Yii::t('app', 'Cannot save task'));
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionTakeCharge($id) {
        $service = $this->loadModel($id);
        if ($service->isAssigned()) {
            $this->renderPartial('_serviceRow', array(
                'service' => $service
            ));
            return;
        }
        $operator = Yii::app()->user->model;
        $service->takeCharge($operator);
        $this->renderPartial('_serviceRow', array(
            'service' => $service
        ));
    }

    public function actionReleaseCharge($id) {
        $service = $this->loadModel($id);
        $operator = Yii::app()->user->model;
        $service->releaseCharge($operator);
        $this->renderPartial('_serviceRow', array(
            'service' => $service
        ));
    }

    public function actionGetStatus($id) {
        $service = $this->loadModel($id);
        $this->renderPartial('_serviceRow', array(
            'service' => $service
        ));
    }

    public function actionReleaseAllPerUser() {
        $user_id = Yii::app()->user->id;
        foreach (Service::model()->byAssignedOperator($user_id)
                ->findAll() as $service)
            $service->releaseCharge();

        Yii::app()->user->setFlash('success', Yii::t('app', 'All tasks have been released.'));
        Yii:
        app()->end();
    }

    public function actionConfirmAllEvents($id, $url) {
        $events = Event::model()->byService($id)
                ->notClosedYet()
                ->findAll();

        $user = user();

        foreach ($events as $ev) {
            $ev->approve($user);
        }

        Yii::app()->user->setFlash('success', Yii::t('app', 'Events successfully confirmed.'));

        $this->redirect($url);
    }

}
