<?php

class GatePresenter extends SimpleDelegator {

  public function getStatusClass()
  {
    return strtolower("status-".$this->Status);
  }

  public function getLastSignalTime()
  {
    $time = $this->LastLifeSignal;
    if($time == null)
    	return null;
    
    return $time->format('H:i');
  }

  public function getLastSignalDate()
  {
    $date = $this->LastLifeSignal;
    return DateHelper::formatISO9075Date($date);
  }

  public function getLastViolationMinutes()
  {
    $preferences = param('gateStatus');
    return $preferences['lastViolationMinutes'];
  }

  public function getLastViolationDays()
  {
    return $this->getLastViolationMinutes() / (24 * 60);
  }

  public function getRecentlyViolations()
  {
    $seconds = $this->getLastViolationMinutes() * 60;
    return Event::model()->byGate($this->target)->recently($seconds)->count();
  }

  public function getRecentlyViolations_New()
  {
    $seconds = $this->getLastViolationMinutes() * 60;
    return Event::model()->byGate($this->target)->recently($seconds, paramdeep('gateStatus', 'newEvents_TimeField'))->new()->count();
  }

  public function getRecentlyViolations_Validated()
  {
    $seconds = $this->getLastViolationMinutes() * 60;
    return Event::model()->byGate($this->target)->recently($seconds, paramdeep('gateStatus', 'validatedEvents_TimeField'))->validated()->count();
  }
  
  public function getRecentlyViolations_Exported()
  {
    $seconds = $this->getLastViolationMinutes() * 60;
    return Event::model()->byGate($this->target)->recently($seconds, paramdeep('gateStatus', 'exportedEvents_TimeField'))->exported()->count();
  }

  public function getRecentlyAlertsCount($type)
  {
    $seconds = $this->getLastViolationMinutes() * 60;
    return Alert::model()->byGate($this->target->Gate)->byType($type)->recently($seconds)->count();
  }
  
  public function getRecentTransits($date)
  { 
    $result = query('SELECT SUM(Counter) AS cnt FROM statstable WHERE Gate=:gt AND StartDateTime >= :tm', array(':gt'=>$this->Gate,':tm'=>$date));
    if(is_numeric($result->cnt))
      return $result->cnt;
    else 
      return 0;      
  }
  
  public function getRecentTransitsDay()
  {
    return $this->getRecentTransits(DateHelper::ensureObjectEx()->getToday());  
  }
  
  public function getRecentTransitsWeek()
  {
    return $this->getRecentTransits(DateHelper::ensureObjectEx()->getFirstDayOfWeek());  
  }
  
  public function getRecentTransitsMonth()
  {
    return $this->getRecentTransits(DateHelper::ensureObjectEx()->getFirstDayOfMonth());  
  }
  
  public function getDeviceModel()
  {
  	$deviceModel = $this->device_model;
  	if($deviceModel != null)
  		return t($deviceModel);
  	
  	return $this->GateType;
  }
  

}
