<?php

class EventController extends Controller {

    public function filters() {
        return array(
            array(
                'application.filters.SyslogFilter - numOfEventsToBeClosed, CodeDescription, statusBox'
            )
        );
    }

    public function countOtherViolationsForPlate($plate, $behaviorTag) {
        /*  	
          $sql = "
          select
          s.plate as plate
          ,b.tag as tag
          ,count(*) as cnt
          from storicotable s
          inner join events_behavior eb on s.id=eb.id_event
          inner join behavior b on eb.id_behavior=b.id
          where s.plate=:plate and (eb.validation_result is null or eb.validation_result <> 'no_validation')
          and b.tag=:tag
          group by s.plate,b.tag
          ";
          $result = query ( $sql, array (
          ':plate' => $plate,
          ':tag' => $behaviorTag
          ), false, false );

         */
        $sql = "
    	select s.plate as plate, b.tag as tag, count(*) as cnt from
   		(
    		select id , plate
    		from storicotable
    		where plate=:plate
    	) s
    	left join events_behavior eb on s.id=eb.id_event
    	left join behavior b on eb.id_behavior=b.id
    	where  (eb.validation_result is null or eb.validation_result <> 'no_validation')
    	and b.tag=:tag
    	";

        $result = query($sql, array(
            ':plate' => $plate,
            ':tag' => $behaviorTag
                ), false, false);


        if (count($result) > 0) {
            $row = array_first($result);
            if (isset($row ['cnt']))
                return $row ['cnt'];
        }

        return 0;
    }

    public function actionDelete($id, $returnUrl = null) {
        if (!paramdeep('events', 'deleteEnabled'))
            access_denied_check(null, true, t("Cannot delete an event"));
        access_denied_check('event_delete');

        if ($returnUrl == null)
            $returnUrl = url('');

        $event = $this->loadEvent($id, false);
        $event->elimina();

        $this->redirect($returnUrl);
    }

    public function actionQueued() {
        access_denied_check('violations_queued');

        $model = new QueuedEventsForm ();

        Yii::import('bootstrap.widgets.TbActiveForm');
        $form = new TbActiveForm($this);

        $dates = query('SELECT min(starttime) as minDate,max(starttime) as maxDate FROM storicotable', array(), true, true);
        if ($dates == null) {
            $dates = new CArray ();
            $dates->minDate = new DateTimeEx ();
            $dates->maxDate = new DateTimeEx ();
        } else {
            $dates->minDate = new DateTimeEx($dates->minDate);
            $dates->maxDate = new DateTimeEx($dates->maxDate);
        }

        $minDate = $dates->minDate;
        $model->startDate = $minDate->toDateString();

        $maxDate = $dates->maxDate;
        $model->endDate = $maxDate->toDateString();

        $timeRangeValues = array(
            'min' => 0,
            'max' => 5,
            'step' => 1
        );
        $model->timeRange = 4;

        if (isset($_REQUEST ['QueuedEventsForm'])) {
            $results = array();

            $model->attributes = $_REQUEST ['QueuedEventsForm'];
            if ($model->validate()) {
                
            }
        }

        $this->render('queued', get_defined_vars());
    }

    public function actionIndex() {
        $this->redirect(url('/'));
    }

    public function actionStatusBox() {
        $time_start = microtime(true); 
        $preferences = param('gateStatus');
        $minutes = $preferences ['lastViolationMinutes'];
        $seconds = $minutes * 60;
        /** Mod. Cache Queries 18.02.2019 Ng. */ 
        if (Yii::app()->params['cached_queries']) {
        $recentlyViolations_New = Event::model()->cache(600)->recentlyForCache($seconds, paramdeep('gateStatus', 'newEvents_TimeField'))
                ->new()
                ->count();
        $recentlyViolations_Validated = Event::model()->cache(600)->recentlyForCache($seconds, paramdeep('gateStatus', 'validatedEvents_TimeField'))
                ->validated()
                ->count();
        $recentlyViolations_Exported = Event::model()->cache(600)->recentlyForCache($seconds, paramdeep('gateStatus', 'exportedEvents_TimeField'))
                ->exported()
                ->count();
        $lastViolationDays = $minutes / (24 * 60);
        }else{
            $recentlyViolations_New = Event::model()->recentlyForCache($seconds, paramdeep('gateStatus', 'newEvents_TimeField'))
                ->new()
                ->count();
            $recentlyViolations_Validated = Event::model()->recentlyForCache($seconds, paramdeep('gateStatus', 'validatedEvents_TimeField'))
                ->validated()
                ->count();
            $recentlyViolations_Exported = Event::model()->recentlyForCache($seconds, paramdeep('gateStatus', 'exportedEvents_TimeField'))
                ->exported()
                ->count();
            $lastViolationDays = $minutes / (24 * 60);
        }
        $this->renderPartial('statusBox', array(
            'recentlyViolations_New' => $recentlyViolations_New,
            'recentlyViolations_Validated' => $recentlyViolations_Validated,
            'recentlyViolations_Exported' => $recentlyViolations_Exported,
            'lastViolationDays' => $lastViolationDays
        ));
        Yii::log("\t Time execution \t".(microtime(true) - $time_start)." s", "info", "event.statusBox.145");
    }

    public function actionAjaxWhitelistSmartTips() {
        $vars = array();

        //$permissions = array();

        $event = array_get($_REQUEST, "Event", array());

        $gate = array_get($_REQUEST, "internal_gate");

        $timestamp = array_get($_REQUEST, "internal_timestamp");

        $nationality = array_get($event, "custom_nationality");

        // turn the plate uppercase
        $plate = strtoupper(array_get($event, "Plate"));

        // normalize language-specific diacritical signs
        $plate = LanguageHelper::normalizeCharacters($plate);

        $vars = $this->varsForWLSmartTips($event, $gate, $timestamp, $nationality, $plate);

        $disableApproveButtonOnWhitelistedEvent = false;
        if ((count($vars ['permessiAttivi']) > 0) && paramdeep('validation', 'disableApproveButtonOnWhitelistedEvent')
        ) {
            $disableApproveButtonOnWhitelistedEvent = true;
        }

        $html = $this->renderPartial("_eventBehavior_WhiteList_SmartTips", $vars, true);

        echo json_encode(
                array(
                    html => $html,
                    import_running => $importRunning,
                    disable_approve_button_on_whitelisted_event => $disableApproveButtonOnWhitelistedEvent
                )
        );
    }

    public function varsForWLSmartTips($event, $gate, $timestamp, $nationality, $plate) {


        // turn the plate uppercase and remove non alphanumeric characters, if any
        $plate = strtoupper($plate);
        $plate = preg_replace("/[^A-Za-z0-9]/", '', $plate);

        $permessi = PlateAuthorization::findSmartByPlate(
                        $plate, $nationality, PlateAuthorization::FIND_SMART_BY_PLATE_FILTERUSERLIST_WHITELIST
        );



        $liste = array();
        $nomiListe = array();
        $permessiAttivi = array();
        foreach ($permessi as $p) {

            if (!in_array($p->IDLista, $liste)) {
                $liste[] = $p->IDLista;
                $nomiListe[$p->IDLista] = $p->Lista;
            }
            if ($p->allowed($gate, $timestamp)) {
                $permessiAttivi[] = $p;
            }
        }


        $Lists = PlateList::model()->importRunning()->findAll();



        $importRunning = (count($Lists) > 0);



        $vars ['gate'] = $gate;
        $vars ['timestamp'] = $timestamp;
        $vars ['nationality'] = $nationality;
        $vars ['plate'] = $plate;
        $vars ['permessi'] = $permessi;
        $vars ['liste'] = $liste;
        $vars ['nomiListe'] = $nomiListe;
        $vars ['permessiAttivi'] = $permessiAttivi;

        return $vars;
    }

    public function actionIndexFilter($service, $scope = null, $toValidateOnly = null) {
        set_time_limit(0);

        $service = Service::model()->findByPk((int) $service);

        if (!isset($service->assignedOperator) || !$service->isAssignedTo(Yii::app()->user->id))
            access_denied_check(null, true);

        if (isset($scope)) {
            if (isset($toValidateOnly) && $toValidateOnly) {
                $events = call_user_func_array(array(
                    $service,
                    $scope
                        ), array(
                    array(
                        'condition' => "validation_result is NULL or validation_result=''"
                    )
                ));
            } else {
                $events = call_user_func(array(
                    $service,
                    $scope
                ));
            }
        } else
            $events = $service->events;

        if (count($events) > 0) {
            $events = array_sort($events, function ($x, $y) {
                return DateTimeEx::compareStatic($x->StartTime, $y->StartTime);
            });

            $queue = UserEventQueue::model()->findByAttributes(array(
                'id_user' => Yii::app()->user->id,
                'id_run' => $service->ID
            ));

            if (!isset($queue))
                $queue = new UserEventQueue ();

            $queue->id_user = Yii::app()->user->id;
            $queue->id_run = $service->ID;
            $queue->queueEvents($events);
            $queue->save();
            $firstEvent = $queue->firstEvent;

            // $this->redirect(array("event/edit/{$firstEvent->ID}"));
       
            $this->redirect(array(
                'event/edit',
                'id' => $firstEvent->ID,
                'service' => $service->ID,
                'scope' => $scope,
                'toValidateOnly' => $toValidateOnly
            ));
        } else
            $this->render('events_completed');
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Event('searchAll');
        $model->unsetAttributes(); // clear any default values

        if (isset($_GET ['Event']))
            $model->attributes = $_GET ['Event'];
        else
            $model->ID = - 1;
        
        //var_dump($_REQUEST);

        $model->id_run = $_REQUEST ['run_id'];
        $model->ValidatedBy = $_REQUEST ['user_id'];
        $model->searchColor = $_REQUEST ['vehicle_color'];
        $model->searchBookmarked = $_REQUEST ['searchBookmarked'] == 1;
        $model->searchByResult = $_REQUEST ['event_result'];

        if ($_REQUEST ['exportbtn'] == t('Export')) {
            access_denied_check('export_events');

            $dataProvider = $model->searchAll(true);

            $csv = new ECSVExport($dataProvider);

            $content = $csv->toCSV();

            $nowDateTime = new DateTime ();

            $fileName = "Events_" . $nowDateTime->format("Y_m_d_H_i_s") . ".csv";

            Yii::app()->getRequest()
                    ->sendFile($fileName, $content, "text/csv", false);

            exit();
        }

        $this->render('admin', array(
            'model' => $model
        ));
    }

    public function actionView($id) {
        $event = $this->loadEvent($id, true);

        $vars = $this->varsForWLSmartTips($event, $event->gate->Gate, $event->StartTime, $event->custom_nationality, $event->Plate);




        if (isset($event->alert)) {
            $operator = Yii::app()->user->model;
            $this->render('/alert/viewEvent', array(
                'alert' => $event->alert,
                'event' => $event,
                'editEnable' => $event->alert->canEdit($operator->id),
                'varsForWL' => $vars
            ));
            return;
        }

        $this->render('viewEvent', array(
            'event' => $event,
            'varsForWL' => $vars
        ));
    }

    private function preloadNextEventEdit($eventId, $service, $scope, $toValidateOnly) {

        // fetch next event data
        $event = $this->loadEvent($eventId, false);
        $queue = $this->loadEventQueue($event);
        if (!$queue) {
            // there is no "queue", so there is nothing to prefetch
            return;
        }
        $nextEvent = $queue->getNextEvent($event);
        if (!$nextEvent) {
            // there is no "next event", so there is nothing to prefetch
            return;
        }

        // set cache-control for event/edit page, so it is cached when the
        // prefetch is done and the cached version is used when the user
        // requests the page
        $expires = 300;  // secs
        header("Content-Type: text/html; charset: UTF-8");
        header("Cache-Control: max-age={$expires}, public, s-maxage={$expires}");
        header("Pragma: ");
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');

        //
        // insert prefetch links to next event edit page
        //
  	
  	// "prefetch" is needed for both firefox and explorer
        Yii::app()->clientScript->registerLinkTag(
                "prefetch", NULL, Yii::app()->createUrl('event/edit', array(
                    'id' => $nextEvent->ID,
                    'service' => $service,
                    'scope' => $scope,
                    'toValidateOnly' => $toValidateOnly
                )), NULL, array()
        );

        // "prerender" is needed for chrome
        Yii::app()->clientScript->registerLinkTag(
                "prerender", NULL, Yii::app()->createUrl('event/edit', array(
                    'id' => $nextEvent->ID,
                    'service' => $service,
                    'scope' => $scope,
                    'toValidateOnly' => $toValidateOnly
                )), NULL, array()
        );
    }
    
    
    /** Ticket NaN 06-02-2019 -> Double view edit design. Waiting for one design for all events's validation */       
    public function renderValidator($event,$eventBehaviors,$queue, $service, $scope, $toValidateOnly, $suggestedCodes){

        $gateBehaviors = array();

        $gate = $event->gate;
        if ($gate != null) {
            $gbs = $gate->gateBehavior;
            if ($gbs != null)
                $gateBehaviors = $gbs;
        }

        if(sizeof($eventBehaviors) == 1){
            if($eventBehaviors[0]->behavior->name == "mean speed violation"){
                $this->render('edit', array(
                    'event' => $event,
                    'gateBehaviors' => $gateBehaviors,
                    'eventBehaviors' => $eventBehaviors,
                    'queue' => $queue,
                    'service' => $service,
                    'scope' => $scope,
                    'toValidateOnly' => $toValidateOnly,
                    'suggestedCodes' => $suggestedCodes
                ));
            }else{
                $this->render('edit_old', array(
                    'event' => $event,
                    'gateBehaviors' => $gateBehaviors,
                    'eventBehaviors' => $eventBehaviors,
                    'queue' => $queue,
                    'service' => $service,
                    'scope' => $scope,
                    'toValidateOnly' => $toValidateOnly,
                    'suggestedCodes' => $suggestedCodes
                ));
            }
        }else{

            $this->render('edit_old', array(
                'event' => $event,
                'gateBehaviors' => $gateBehaviors,
                'eventBehaviors' => $eventBehaviors,
                'queue' => $queue,
                'service' => $service,
                'scope' => $scope,
                'toValidateOnly' => $toValidateOnly,
                'suggestedCodes' => $suggestedCodes
            ));
            
        }


    }

    public function actionEdit($id, $service = null, $scope = null, $toValidateOnly = null) {

        $this->preloadNextEventEdit($id, $service, $scope, $toValidateOnly);

        set_time_limit(0);
        // ini_set('max_execution_time', 300); //300 seconds = 5 minutes

        $event = $this->loadEvent($id, false);

        if ($event->isExported()) {
            access_denied_check(null, true, t('Cannot edit an exported event.'));
            return;
        }

        $eventBehaviors = $event->eventBehaviorsToValidate;

        $gateBehaviors = array();

        $gate = $event->gate;
        if ($gate != null) {
            $gbs = $gate->gateBehavior;
            if ($gbs != null)
                $gateBehaviors = $gbs;
        }

        $queue = $this->loadEventQueue($event);
        if ($queue == null) {
            $serviceObj = $event->service;
            if (!isset($serviceObj->assignedOperator) || !$serviceObj->isAssignedTo(Yii::app()->user->id))
                access_denied_check(null, true);
            if (isset($scope)) {
                if (isset($toValidateOnly) && $toValidateOnly)
                    $events = call_user_func_array(array(
                        $serviceObj,
                        $scope
                            ), array(
                        array(
                            'condition' => "validation_result is NULL or validation_result=''"
                        )
                    ));
                else
                    $events = call_user_func(array(
                        $serviceObj,
                        $scope
                    ));
            } else
                $events = $serviceObj->events;

            $queue = new UserEventQueue ();

            $queue->id_user = Yii::app()->user->id;
            $queue->id_run = $serviceObj->ID;
            $queue->queueEvents($events);
            $queue->save();
        }

        $suggestedCodes = $this->getSuggestedCodes($event);

        if (isEmpty($event->custom_nationality))
            if (paramdeep('events', 'nationality', 'default') !== false) {

                $event->custom_nationality = paramdeep('events', 'nationality', 'default');
            }
        /** Ticket NaN 06-02-2019 -> Double view edit design. Waiting for one design for all events's validation */
       $this->renderValidator($event,$eventBehaviors,$queue, $service, $scope, $toValidateOnly, $suggestedCodes);
        /*---------------------------------------------------------------*/
       
        
    }

    public function actionUpdateRelease($id, $service = null, $scope = null, $toValidateOnly = null) {
        $serviceId = $service;

        $event = $this->loadEvent($id, false);
        $eventBehaviors = $event->eventBehaviorsToValidate;

        $queue = $this->loadEventQueue($event);

        $service = new EventUpdateService($event, $eventBehaviors, $_POST);
        if ($service->hasErrors()) {
            $event = $service->event;
            $eventBehaviors = $service->eventBehaviors;

            $suggestedCodes = $this->getSuggestedCodes($event);

            Yii::app()->user->setFlash('error', Yii::t('app', 'Error. Please, check the form for more information before continue.'));
            /** Ticket NaN 06-02-2019 -> Double view edit design. Waiting for one design for all events's validation */
            /*
            $this->render('edit', array(
                'event' => $event,
                'eventBehaviors' => $eventBehaviors,
                'queue' => $queue,
                'service' => $serviceId,
                'scope' => $scope,
                'toValidateOnly' => $toValidateOnly,
                'suggestedCodes' => $suggestedCodes
            ));*/
            $this->renderValidator($event,$eventBehaviors,$queue, $serviceId, $scope, $toValidateOnly, $suggestedCodes);
            /*----------------------------------------------------*/
        } else {

            $this->updateVehicleGeneratedByEvent($event);

            Yii::app()->user->setFlash('success', Yii::t('app', 'Event #{event_id} saved successfully and service released.', array(
                        '{event_id}' => $event->ID
            )));

            $serviceObj = Service::findById($serviceId);
            $operator = user()->model;
            $serviceObj->releaseCharge($operator);

            $this->redirectTo(''); // redirect alla home page
        }
    }

    public function actionUpdate($id, $service = null, $scope = null, $toValidateOnly = null) {
        $serviceId = $service;

        $event = $this->loadEvent($id, false);

        $eventBehaviors = $event->eventBehaviorsToValidate;

        $queue = $this->loadEventQueue($event);


        $service = new EventUpdateService($event, $eventBehaviors, $_POST);



        if ($service->hasErrors()) {
            $event = $service->event;
            $eventBehaviors = $service->eventBehaviors;

            $suggestedCodes = $this->getSuggestedCodes($event);
            Yii::app()->user->setFlash('error', Yii::t('app', 'Error. Please, check the form for more information before continue.'));
             /** Ticket NaN 06-02-2019 -> Double view edit design. Waiting for one design for all events's validation */       
            /*
             $this->render('edit', array(
                'event' => $event,
                'eventBehaviors' => $eventBehaviors,
                'queue' => $queue,
                'service' => $serviceId,
                'scope' => $scope,
                'toValidateOnly' => $toValidateOnly,
                'suggestedCodes' => $suggestedCodes
            ));*/
            /*--------------------------------------------------------------------*/
        $this->renderValidator($event,$eventBehaviors,$queue, $serviceId, $scope, $toValidateOnly, $suggestedCodes);
            /*---------------------------------------------------------------*/
       

        } else {
            if (isset($_POST['croppedImagesData']) && !empty($_POST['croppedImagesData'])) {
                //  procedura: 
                //  per ogni immagine presente nell'array:
                //      - cancello eventuali crop da db
                //      - cancello eventuali crop da fs
                //      - creo nuovo crop a db
                //      - creo nuovo crop su fs
                //      - cancello eventuali entry precedenti nella tabella images_roi
                //      - creo nuova entry nella tabella images_roi
                $decodedImagesDataArray = json_decode($_POST['croppedImagesData'], true);
                foreach ($decodedImagesDataArray as $currentImageData) {
                    $significantBlobId = "";
                    switch ($currentImageData['overlayId']) {
                        case "first-face":
                            $significantBlobId = 7000;
                            break;
                        case "second-face":
                            $significantBlobId = 7100;
                            break;
                        case "first-plate-bw":
                            $significantBlobId = 8000;
                            break;
                        case "second-plate-bw":
                            $significantBlobId = 8100;
                            break;
                    }
                    $tmpMedia = MediaAttachment::model();
                    $tmpMedia->setSignificantPhotoBlobIdBw($significantBlobId);
                    $tmpMedia->byEventIds($event->ExtraInfoID);
                    $tmpMedia->preview();
                    $foundCrop = $tmpMedia->find();
                    if (isset($foundCrop)) {
                        unlink(pathCombine(Yii::app()->params['photoBasePath'], $foundCrop->BlobFileName));
                        $foundCrop->delete();
                    }

                    $tmpMedia = MediaAttachment::model();
                    $tmpMedia->setSignificantPhotoBlobIdBw(1000);
                    $tmpMedia->byEventIds($event->ExtraInfoID);
                    $tmpMedia->preview();
                    $refForPath = $tmpMedia->find();
                    if (isset($refForPath)) {
                        $pathToUse = $refForPath->BlobFileName;
                    }

                    $imgData = explode(',', $currentImageData['base64']);
                    $newPath = str_replace(basename($pathToUse), $currentImageData['overlayId'] . ".jpg", $pathToUse);
                    file_put_contents(pathCombine(Yii::app()->params['photoBasePath'], $newPath), base64_decode($imgData[1]));

                    $dateToPut = new DateTime();

                    $newCropToSave = new MediaAttachment();
                    $newCropToSave->EventID = $event->ExtraInfoID;
                    $newCropToSave->BlobIDSelected = 0;
                    $newCropToSave->BlobDataLength = 0;
                    $newCropToSave->BlobID = $significantBlobId;
                    $newCropToSave->type = "image/jpeg";
                    $newCropToSave->Description = $currentImageData['overlayId'];
                    $newCropToSave->FullTime = $dateToPut->format('H:i:s.u - d/m/Y');
                    $newCropToSave->epoch = $dateToPut->format("Y-m-d H:i:s");
                    $newCropToSave->BlobFileName = $newPath;
                    $newCropToSave->extrainfo = "";
                    $newCropToSave->save();

                    $selectedCriteria = new CDbCriteria();
                    $selectedCriteria->condition = "event_id =" . $event->ExtraInfoID . " and src_image_type='" . $currentImageData['overlayId'] . "'";
                    $foundCrop = ImagesRoi::model()->find($selectedCriteria);
                    if (isset($foundCrop)) {
                        $foundCrop->delete();
                    }

                    $imageRoiToAdd = new ImagesRoi();
                    $imageRoiToAdd->image_id = $currentImageData['imageId'];
                    $imageRoiToAdd->event_id = $event->ExtraInfoID;
                    $imageRoiToAdd->src_image_type = $currentImageData['overlayId'];
                    $imageRoiToAdd->roi_x = $currentImageData['roi_x'];
                    $imageRoiToAdd->roi_y = $currentImageData['roi_y'];
                    $imageRoiToAdd->roi_width = $currentImageData['roi_width'];
                    $imageRoiToAdd->roi_height = $currentImageData['roi_heigth'];
                    $imageRoiToAdd->action = "crop";
                    $imageRoiToAdd->save();
                }
            }

            $this->updateVehicleGeneratedByEvent($event);
            
            if (!paramdeep('report', 'byWorkPeriod')) {
                $event->service->id_user_validating = $event->service->in_charge_to;
                $event->service->save();
            }

            Yii::app()->user->setFlash('success', Yii::t('app', 'Event #{event_id} saved successfully.', array(
                        '{event_id}' => $event->ID
            )));
            $this->redirect(array(
                'event/updateNext',
                'currentEventId' => $id,
                'service' => $serviceId,
                'scope' => $scope,
                'toValidateOnly' => $toValidateOnly
            ));
        }
    }

    /**
     *
     * @param int $id          
     * @param boolean $readOnly          
     * @throws CHttpException
     * @return Event
     */
    public function loadEvent($id, $readOnly) {
        $model = Event::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));

        $service = $model->service;
        if (!user()->checkAccess('event_view_all') && !$readOnly)
            if (!isset($service->assignedOperator) || !$service->isAssignedTo(Yii::app()->user->id))
                access_denied_check(null, true, t("The event does not belong to a service taken by you."));

        set_time_limit(0);

        return $model;
    }

    /**
     *
     * @param Event $event          
     * @throws CHttpException
     * @return UserEventQueue
     */
    public function loadEventQueue($event) {
        if ($event->service === null)
            throw new CHttpException(404, Yii::t('app', 'Cannot find task for event #{event_id}.', array(
                '{event_id}' => $event->ID
            )));

        return UserEventQueue::model()->findByAttributes(array(
                    'id_user' => Yii::app()->user->id,
                    'id_run' => $event->service->ID
        ));
    }

    public function actionSuspend($id, $service = null, $scope = null, $toValidateOnly = null) {
        $serviceId = $service;
        $event = $this->loadEvent($id, false);
        $eventBehaviors = $event->eventBehaviors;

        $queue = $this->loadEventQueue($event);

        $service = new EventUpdateService($event, $eventBehaviors, $_POST);

        if ($service->hasErrors()) {
            $event = $service->event;
            $eventBehaviors = $service->eventBehaviors;

            $suggestedCodes = $this->getSuggestedCodes($event);

            Yii::app()->user->setFlash('error', Yii::t('app', 'Error. Please, check the form for more information before continue.'));
            /** Ticket NaN 06-02-2019 -> Double view edit design. Waiting for one design for all events's validation */       
            /*
            $this->render('edit', array(
                'event' => $event,
                'eventBehaviors' => $eventBehaviors,
                'queue' => $queue,
                'service' => $serviceId,
                'scope' => $scope,
                'toValidateOnly' => $toValidateOnly,
                'suggestedCodes' => $suggestedCodes
            ));*/
            /*--------------------------------------------------------------------*/
            $this->renderValidator($event,$eventBehaviors,$queue, $serviceId, $scope, $toValidateOnly, $suggestedCodes);
            /*---------------------------------------------------------------*/
            
        } else {

            $event->suspend();

            Yii::app()->user->setFlash('success', Yii::t('app', 'Event #{event_id} saved successfully.', array(
                        '{event_id}' => $event->ID
            )));
            // $this->redirect(array('event/updateNext', 'currentEventId'=>$id));

            $this->redirect(array(
                'event/updateNext',
                'currentEventId' => $id,
                'service' => $serviceId,
                'scope' => $scope,
            ));
        }

        // $event = $this->loadEvent($id);
        // $event->suspend();
        // $this->actionUpdateNext($event->ID);
    }

    public function actionUpdateNext($currentEventId, $service = null, $scope = null, $toValidateOnly = null) {
        $serviceId = $service;
        $event = $this->loadEvent($currentEventId, false);
        $queue = $this->loadEventQueue($event);

        $nextEvent = $queue->getNextEvent($event);
        if ($nextEvent == null) {
            $this->render('events_completed');
            return;
        }

        //$this->actionEdit($nextEvent->ID, $serviceId, $scope, $toValidateOnly);
        // $this->redirect(array("event/edit/{$nextEvent->ID}"));
        $this->redirect(array(
            'event/edit',
            'id' => $nextEvent->ID,
            'service' => $serviceId,
            'scope' => $scope,
            'toValidateOnly' => $toValidateOnly,
        ));
    }

    public function actionUpdatePrevious($currentEventId, $service = null, $scope = null, $toValidateOnly = null) {
        $serviceId = $service;
        $event = Event::model()->findbyPk($currentEventId);
        $queue = $this->loadEventQueue($event);

        $previousEvent = $queue->getPreviousEvent($event);

        //$this->actionEdit($previousEvent->ID, $serviceId, $scope, $toValidateOnly);
        // $this->redirect(array("event/edit/{$previousEvent->ID}"));
        $this->redirect(array(
            'event/edit',
            'id' => $previousEvent->ID,
            'service' => $serviceId,
            'scope' => $scope,
            'toValidateOnly' => $toValidateOnly,
        ));
    }

    public function actionReportImage($id, $cropImage = TRUE) {
        $media = MediaAttachment::model()->byEventIDs($id)
                ->byPhotoReport()
                ->find();

        $cropOk = FALSE;

        $jpg = new JpgImage ();
        /*----Mod. Unable to see images -- Task Id #12757024 06-02-2019. Ng ---*/
        /*$jpg->load($media->url);*/
        $jpg->load($media->BaseUrl);

        header("Content-Type: image/jpg");

        if ($cropImage == TRUE) {
            $jpgtool = new JPGTools($media->url);

            $XmlArray = $jpgtool->readKriaInfo();

            if ($XmlArray !== FALSE) {
                $plateX = - 1;
                $plateY = - 1;
                $plateWidth = - 1;
                $plateHeight = - 1;

                if (array_key_exists("PlateMinX", $XmlArray) && array_key_exists("PlateMaxX", $XmlArray) && array_key_exists("PlateMinY", $XmlArray) && array_key_exists("PlateMaxY", $XmlArray)) {
                    if ($XmlArray ["PlateMinX"] < $XmlArray ["PlateMaxX"] && $XmlArray ["PlateMinY"] < $XmlArray ["PlateMaxY"]) {
                        $plateX = $XmlArray ["PlateMinX"];
                        $plateY = $XmlArray ["PlateMinY"];
                        $plateWidth = $XmlArray ["PlateMaxX"] - $plateX;
                        $plateHeight = $XmlArray ["PlateMaxY"] - $plateY;
                    }
                }

                if (array_key_exists("PlateLeft", $XmlArray) && array_key_exists("PlateRight", $XmlArray) && array_key_exists("PlateTop", $XmlArray) && array_key_exists("PlateBottom", $XmlArray)) {
                    if ($XmlArray ["PlateLeft"] < $XmlArray ["PlateRight"] && $XmlArray ["PlateTop"] < $XmlArray ["PlateBottom"]) {
                        $plateX = $XmlArray ["PlateLeft"];
                        $plateY = $XmlArray ["PlateTop"];
                        $plateWidth = $XmlArray ["PlateRight"] - $plateX;
                        $plateHeight = $XmlArray ["PlateBottom"] - $plateY;
                    }
                }

                if ($plateX > 0 && $plateY > 0 && $plateWidth > 0 && $plateHeight > 0) {
                    // params
                    $wiap = Yii::app()->params ['webImageAccess'];

                    // carico i parametri di crop
                    $defTopMar = $wiap ['defaultTopMargin'];
                    $defBtmMar = $wiap ['defaultBottomMargin'];
                    $defLftMar = $wiap ['defaultLeftMargin'];
                    $defRgtMar = $wiap ['defaultRightMargin'];
                    $defBndSiz = $wiap ['defaultBottomBandSize'];

                    // controllo che non escano dall'immagine originale
                    $defTopMar = $jpg->legalizeY($defTopMar);
                    $defBtmMar = $jpg->legalizeY($defBtmMar);
                    $defLftMar = $jpg->legalizeX($defLftMar);
                    $defRgtMar = $jpg->legalizeX($defRgtMar);
                    $defBndSiz = $jpg->legalizeY($defBndSiz);

                    // creo i parametri di crop e controllo che non escano dall'immagine originale
                    $cropX = $jpg->legalizeX($plateX - $defLftMar);
                    $cropY = $jpg->legalizeY($plateY - $defTopMar);
                    $cropWidth = $jpg->legalizeWidth($cropX, $plateWidth + $defLftMar + $defRgtMar);
                    $cropHeight = $jpg->legalizeHeight($cropY, $plateHeight + $defTopMar + $defBtmMar);

                    // taglio la banda, se coinvolta
                    if (($cropY + $cropHeight) > ($jpg->height() - $defBndSiz)) {
                        $banda = ($cropY + $cropHeight) - ($jpg->height() - $defBndSiz);
                        $cropHeight = $cropHeight - $banda;
                    }

                    // croppo
                    $croppedImage = $jpg->crop($cropX, $cropY, $cropWidth, $cropHeight);
                    if ($croppedImage)
                        if ($croppedImage->output())
                            $cropOk = TRUE;
                }
            }
        }

        if (!$cropOk)
            $jpg->output();
    }

    public function actionViolationDocumentPreview($violationDocumentId) {
        $doc = ViolationDocument::model()->findByPk($violationDocumentId);

        if ($doc == null)
            throw new CHttpException(404, 'Invalid request. Violation Document not found.');

        $this->render('violationDocumentPreview', array(
            'violationDocument' => $doc
        ));
    }

    public function actionReport($id) {
        access_denied_check('show_event_report');

        $event = $this->loadEvent($id, false);

        $mediaUrl = Yii::app()->createAbsoluteUrl('event/ReportImage', array(
            'id' => $event->ExtraInfoID
        ));

        $templateParams = array(
            'event' => $event,
            'photoReportUrl' => $mediaUrl
        );

        $this->layout = '//layouts/print';

        $this->render('eventReport', $templateParams);
    }

    public function actionExportPdf($id) {
        $event = $this->loadEvent($id, true);
        //$a = $event->photo;
        if ($event == null)
            throw new CHttpException(404, 'Invalid request. Event not found.');

        $certificate = Yii::app()->params ['exportPdfCertificate'];
        $certificateFound = file_exists($certificate);
        $certificatewarning = $certificateFound ? "" : Yii::t('app', 'NOT SIGNED');

        $mediaUrl = Yii::app()->createAbsoluteUrl('event/ReportImage', array(
            'id' => $event->ExtraInfoID
        ));
        /**-------BUG Event -> Report -> CITTA DI TORINO Task Id #12757013 06-02-2019. Ng */
        /*$urlTorinoImg = Yii::app()->createAbsoluteUrl('/images/citta_torino.jpg');*/
        $urlCityLog = Yii::app()->createAbsoluteUrl('/images/'.paramdeep('event','report','logo'));
        $urlCityText =paramdeep('event','report','text');
        /*----------------------*/

        // if(!check_page_online($mediaUrl))
        // $mediaUrl = $urlTorinoImg;
        // preparo dati
        $nowISO = DateHelper::formatISO9075DateTime();
        $eventDate = $event->StartTime->format(DateHelper::ISO9075_DATE);
        $eventTime = $event->StartTime->format(DateHelper::ISO9075_TIME);
        $veichleClasses = VehicleTypes::localized();
        $nations = CountryList::localized();
        $challengedSpeed = number_format(CalculateChallengedSpeed::run($event->Speed, Yii::app()->params ['spotSpeedViolation'] ['percentageTolerance'], Yii::app()->params ['spotSpeedViolation'] ['fixedTolerance'], Yii::app()->params ['spotSpeedViolation'] ['toleranceTable']), 2);

        $templateParams = array(
            'event' => $event,
            'mediaUrl' => $mediaUrl,
            'certificatewarning' => $certificatewarning,
            /**-------BUG Event -> Report -> CITTA DI TORINO Task Id #12757013 06-02-2019. Ng  */
            /*'urlTorinoImg' => $urlTorinoImg,*/
            'urlCityLogo'=> $urlCityLog,
            'urlCityText'=> $urlCityText,
            /**------------------------------ */
            'eventDate' => $eventDate,
            'eventTime' => $eventTime,
            'veichleClasses' => $veichleClasses,
            'nations' => $nations,
            'challengedSpeed' => $challengedSpeed
        );

        $this->layout = '//layouts/pdf';

        $html = $this->render('eventPdf', $templateParams, TRUE);

        $fileTitle = t('Event') . "_" . $id;

        $fileTitle = str_replace(' ', '_', $fileTitle);

        if (true) {
           // $html = gzcompress($html, 9);
            Yii::app()->user->setState('htmlPdf', $html);
            /*Mod. 06_02_2019 error: Page Not Found. Task Id #12757024 Ng*/
            $varPreview = TempDataBuffer::instance()->add($html);
            $varData = TempDataBuffer::instance()->add($html);
            /* ------------------------------ */
            $this->redirect(array(
               /*Mod. 06_02_2019 error: Page Not Found. Task Id #12757024 Ng*/
                /* 'pdfExport/ExportPdf',
                'htmlVar' => 'htmlPdf',
                'title' => $fileTitle*/
                'pdfExport/ExportPdf',
                'htmlVarPreview' => $varPreview,
                'htmlVarData' => $varData,
                'title' => $fileTitle

            ));
        } else {
            echo $html;
            exit();
        }
    }

    /**
     *
     * @return number
     */
    public static function getNumOfEventsToBeClosed() {
        $numOfEvents = 0;

        if (Yii::app()->user->checkAccess('create_events_report')) {
            $numOfEvents = Event::model()->approvedOrInvalid()
                    ->notClosedYet()
                    ->byValidator(Yii::app()->user)
                    ->howMany();
        }

        return $numOfEvents;
    }

    public function actionNumOfEventsToBeClosed() {
        $res = array();

        $numOfEvents = self::getNumOfEventsToBeClosed();

        $res ['numOfEventsToBeClosed'] = $numOfEvents;

        echo CJSON::encode($res);

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

    public function actionCodeDescription($code, $eventTag) {
        $vCode = ViolationCode::model()->byName($code)
                ->find();

        if ($vCode == null) {
            echo Yii::t('app', 'no code');
            Yii::app()->end();

            return;
        }

        echo $vCode->description;

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

    public function actionExportToPdf($id) {
        $event = $this->loadEvent($id, true);

        if (isset($event->alert)) {
            $operator = Yii::app()->user->model;

            $html = $this->renderPartial('/alert/viewEvent', array(
                'alert' => $event->alert,
                'event' => $event,
                'editEnable' => $event->alert->canEdit($operator->id)
                    ), true);
        } else {
            $this->layout = '//layouts/pdf';
            $html = $this->render('viewEventPdf', array(
                'event' => $event
                    ), true);
            $html = gzcompress($html, 9);

            $fileTitle = t('Event') . "_" . $id;

            Yii::app()->user->setState('htmlPdf', $html);
            $this->redirect(array(
                'pdfExport/ExportPdf',
                'htmlVar' => 'htmlPdf',
                'title' => $fileTitle
            ));
        }
    }

    private function getSuggestedCodes($event) {
        $suggestedCodes = array();
        $eventBehaviors = $event->eventBehaviors;

        $customVehicleType = $event->custom_vehicle_type;
        $customPropertyType = $event->custom_property_type;

        $challengedSpeed = CalculateChallengedSpeed::run($event->Speed, Yii::app()->params ['spotSpeedViolation'] ['percentageTolerance'], Yii::app()->params ['spotSpeedViolation'] ['fixedTolerance'], Yii::app()->params ['spotSpeedViolation'] ['toleranceTable']);
        $challengedSpeedDelta = $challengedSpeed - $event->speed_limit;
        $hasGoods = null;
        $dangerousGoods = $event->Kemler;
        if (isset($dangerousGoods)) {
            $hasGoods = 0;
            if (strlen($dangerousGoods) > 0)
                $hasGoods = 1;
        }

        foreach ($eventBehaviors as $behav) {
            if ($behav->behavior->tag == Behavior::ILLEGAL_SPOT_SPEED) {
                $suggCode = SpotSpeedArticleWizard::model()->suggestCodes($customVehicleType, $customPropertyType, $challengedSpeedDelta, $event->StartTime);
                if ($suggCode == null)
                    $suggCode = ViolationCode::getUniqueChoiceForBehavior($behav->id_behavior);

                if ($suggCode != null)
                    $suggestedCodes [Behavior::ILLEGAL_SPOT_SPEED] = $suggCode;
            }
            else {
                $suggCode = ViolationCode::getUniqueChoiceForBehavior($behav->id_behavior);
                if ($suggCode != null)
                    $suggestedCodes [$behav->behavior->tag] = $suggCode;
            }
        }

        return $suggestedCodes;
    }

    protected function getCommentSuggestions() {
        $params = new CArray(paramdeep('validation', 'comment', 'autocomplete'));

        if ($params->enabled) {
            $suggestions = array();
            $suggestions[''] = '';

            if ($params->table) {
                foreach (query("SELECT DISTINCT comment FROM events_behavior WHERE comment <> '' AND comment IS NOT NULL", array(), false, false) as $comment) {
                    if (!in_array($comment ['comment'], $suggestions)) {
                        $suggestions [$comment ['comment']] = $comment ['comment'];
                    }
                }
            }

            foreach ($params->custom as $c) {
                if (!in_array($c, $suggestions)) {
                    $suggestions [$c] = $c;
                }
            }

            //$suggestions = array_remove_dup($suggestions);

            return $suggestions;
        } else
            return null;
    }

    protected function getCommentSuggestionsJS() {
        $items = $this->getCommentSuggestions();
        if ($items == null)
            return null;
        return $this->addSuggestionsScript('.autocomment', $items, true);
    }

    protected function addPlateSuggestionsJS(Event $event, $return = false) {
        if ($event != null && $event->hasWildcardPlate()) {
            $values = ExpressionHelper::getPlateValues($event->Plate);
            return $this->addSuggestionsScript('.platefield', $values, $return);
        }
        return null;
    }

    public function actionwhitelistImportContent() {
        $Lists = PlateList::model()->importRunning()->findAll();

        $this->renderPartial(
                '_importWhitelistRunnig', array('plate_lists' => $Lists)
        );
    }

    public function actionIsWhitelistImportRunning() {

        $Lists = PlateList::model()->importRunning()->findAll();

        $importRunning = (count($Lists) > 0);

        echo json_encode(array(import_running => $importRunning));
    }

    public function updateVehicleGeneratedByEvent(Event $event) {

        $v = $event->vehicle;
        if ($v != null) {
            $v->note = "plate changed from " . $v->Targa . " to " . $event->Plate;
            $v->Targa = $event->Plate;

            $v->save();
        }
    }

    public function actionGetIcetraDetails($plate) {
        $access_key = '422bJ2sig2tMT3';
        $secret_key = 'kmsBC9TRWr5DpIg1s4ndSt0l0RrFjow1';

        $baseHost = "https://test-xml.samgongustofa.is";

        $query2 = "/ekja/hradamyndavel/regno/" . $plate;

        $correctGMTDate = gmdate("D, d M Y H:i:s") . " GMT";

        $concatenatedValues = $correctGMTDate . "\n" . "GET" . "\n" .
                $query2 . "\n" . $access_key;
        $SHA256Value = hash_hmac("sha256", utf8_encode($concatenatedValues), $secret_key);
        $signature = base64_encode($SHA256Value);

        $headersArray = array("Content-Type: text/html",
            "X-Icetra-Date: $correctGMTDate",
            "Authorization: ICETRA $access_key:$signature");

        //print_r($headersArray);

        $context = stream_context_create(array(
            'http' => array(
                'method' => 'GET',
                'header' => $headersArray,
                'ignore_errors' => true
            )
        ));

        //print_r($context);
        // Send the request
        $response = file_get_contents($baseHost . $query2, FALSE, $context);
//        print_r(json_decode($response));
//        print_r($http_response_header);
        $response = json_decode($response);

        $resultArray = array();
        $resultArray["plate"] = $plate;
        $resultArray["maker"] = "nope";
        $resultArray["model"] = "nah";
        $resultArray["color"] = "nope";
        $resultArray["firstRegDate"] = "nah";
        $resultArray["latestRegistration"] = "nahnah";
        $resultArray["vehicleGroup"] = "nahnah";

        if ($response !== false && !empty($response->vehicle)) {
            $resultArray["plate"] = $plate;
            $resultArray["maker"] = $response->vehicle->make;
            $resultArray["model"] = $response->vehicle->vehcom;
            $resultArray["color"] = $response->vehicle->color;
            $resultArray["firstRegDate"] = date('d/m/Y H:i:s', strtotime($response->vehicle->firstregdate));
            $resultArray["latestRegistration"] = $response->vehicle->latestregistration;
            $resultArray["vehicleGroup"] = $response->vehicle->vehgroup;
            echo json_encode($resultArray);
        }else{
            echo "NA";
        }
    }
    /**
    * dragonImageObscureChangeXML
    *
    * Receive an XMLHttpRequest POST object, Opens a connection to a MySQL server and change XML content in storicoTable 'ExtraData' and TebTable 'extrainfo'
    *    
    */
    public function actionDragonImageObscureChangeXML(){
        if (Yii::app()->params['selectedbyuserid']) {
        $ImgData = array();
        foreach ($_POST as $key => $value) {
            //Yii::log("\t JSON  -> Key \t".$key." Value -> ".$value, "info", "event.actionDragonImageObscureChangeXML");
            $ImgData[$key] = $value;
        }

        //TebTable query Xml
        
        $eventID = MediaAttachment::model()->findByPk($ImgData['parsedId']);
        $eventID->setPlateRectangleFromDragonImage($ImgData['croppedX'],$ImgData['croppedY'],$ImgData['croppedWidth'],$ImgData['croppedHeight']);
        $eventID->save();

        //StoricoTable query Xml
        
        $event = Event::model()->find('ExtraInfoID=:eiid', array(':eiid' => $eventID->EventID));
       
        $ExtraData = $event->Xml;
        
        $index_selected = ($eventID->BlobID-1000);
        
       if(isset($ExtraData->images_Ids->WhiteListViolation->SelectedByUserID)){
        $ExtraData->images_Ids->WhiteListViolation->SelectedByUserID = strval($index_selected);
        
       }else{
        $selectbyid = $ExtraData->images_Ids->WhiteListViolation->addChild('SelectedByUserID',strval($index_selected));
        $selectbyid->addAttribute('type','dword');
        
       }
       
       $ExtraData->Images->View[$index_selected]->PlateMinX = (int)  $ImgData['croppedX'];
       $ExtraData->Images->View[$index_selected]->PlateMaxX = (int) ($ImgData['croppedX']+$ImgData['croppedWidth']);
       $ExtraData->Images->View[$index_selected]->PlateMinY = (int) $ImgData['croppedY'];
       $ExtraData->Images->View[$index_selected]->PlateMaxY = (int) ($ImgData['croppedY']+$ImgData['croppedHeight']);
      
       $xml_to_save = $ExtraData->asXML();

       $sql="UPDATE ".$event->tableName()." SET ExtraData=CONVERT('".$xml_to_save."',BINARY), ExtraDataLength='".strlen($xml_to_save)."' WHERE ID='".strval($event->ID)."'";
      
       if(!Yii::app()->db->createCommand($sql)->execute()){
        Yii::log("\t Unable to Store ExtraData for event->Id {".$event->ID."} \t", "error", "event.actionDragonImageObscureChangeXML");
       }else{
        Yii::log("\t Stored ExtraData for event->Id {".$event->ID."} \t", "info", "event.actionDragonImageObscureChangeXML");
       }
       
       $sql="UPDATE violation_document SET status='missing' WHERE id_event_behavior=(SELECT ID FROM events_behavior where id_event='".strval($event->ID)."')";
      
       if(!Yii::app()->db->createCommand($sql)->execute()){
        Yii::log("\t Unable to Update Violation_document_Table for event->Id {".$event->ID."} \t", "error", "event.actionDragonImageObscureChangeXML");
       }else{
        Yii::log("\t Updated Violation_document_Table for event->Id {".$event->ID."} \t", "info", "event.actionDragonImageObscureChangeXML");
       }

    }
    }

}
