<?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()
  {
    $preferences = param ( 'gateStatus' );
    $minutes = $preferences ['lastViolationMinutes'];
    $seconds = $minutes * 60;
    
    $recentlyViolations_New = Event::model ()->recently ( $seconds, paramdeep ( 'gateStatus', 'newEvents_TimeField' ) )
      ->new ()
      ->count ();
    $recentlyViolations_Validated = Event::model ()->recently ( $seconds, paramdeep ( 'gateStatus', 'validatedEvents_TimeField' ) )
      ->validated ()
      ->count ();
    $recentlyViolations_Exported = Event::model ()->recently ( $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 
    ) );
  }

  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;
    
    $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);
  	$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()
  	);
  	
  }

  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' );

      }
    
    $this->render ( 'edit', array (
        'event' => $event,
        'gateBehaviors' => $gateBehaviors,
        'eventBehaviors' => $eventBehaviors,
        'queue' => $queue,
        'service' => $service,
        'scope' => $scope,
        'toValidateOnly' => $toValidateOnly,
        'suggestedCodes' => $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.' ) );
      $this->render ( 'edit', array (
          'event' => $event,
          'eventBehaviors' => $eventBehaviors,
          'queue' => $queue,
          'service' => $serviceId,
          'scope' => $scope,
          'toValidateOnly' => $toValidateOnly,
          'suggestedCodes' => $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.' ) );
      $this->render ( 'edit', array (
          'event' => $event,
          'eventBehaviors' => $eventBehaviors,
          'queue' => $queue,
          'service' => $serviceId,
          'scope' => $scope,
          'toValidateOnly' => $toValidateOnly,
          'suggestedCodes' => $suggestedCodes 
      ) );
    }
    else
    {
    	$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.' ) );
      $this->render ( 'edit', array (
          'event' => $event,
          'eventBehaviors' => $eventBehaviors,
          'queue' => $queue,
          'service' => $serviceId,
          'scope' => $scope,
          'toValidateOnly' => $toValidateOnly,
          'suggestedCodes' => $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 ();
    
    $jpg->load ( $media->url );
    
    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 );
    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 
    ) );
    
    $urlTorinoImg = Yii::app ()->createAbsoluteUrl ( '/images/citta_torino.jpg' );
    
    // 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,
        'urlTorinoImg' => $urlTorinoImg,
        '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 );
      $this->redirect ( array (
          'pdfExport/ExportPdf',
          'htmlVar' => 'htmlPdf',
          '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 ();
      
      if ($params->table)
      {
        foreach ( query ( "SELECT DISTINCT comment FROM events_behavior WHERE comment <> '' AND comment IS NOT NULL", array (), false, false ) as $comment )
        {
          $suggestions [] = $comment ['comment'];
        }
      }
      
      foreach ( $params->custom as $c )
      {
        $suggestions [] = $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();
  	}

  }
  
}
