<?php

/**
 * This is the model class for table "ztltable".
 *
 * The followings are the available columns in table 'ztltable':
 * @property string $ID
 * @property string $Descrizione
 * @property string $GateID
 * @property string $TimeID
 * @property string $Transito
 * @property string $epoch
 * @property TimeSchedule time
 * @property Gate gate
 */
class Ztl extends ActiveRecord
{

  const ZTL_TRANSIT_LIMITED = 'Limitato';

  const ZTL_TRANSIT_FREE = 'Transito';

  /**
   * Returns the static model of the specified AR class.
   * 
   * @param string $className
   *          active record class name.
   * @return Ztl the static model class
   */
  public static function model($className = __CLASS__)
  {
    return parent::model ( $className );
  }

  /**
   *
   * @return string the associated database table name
   */
  public function tableName()
  {
    return 'ztltable';
  }

  /**
   *
   * @return array validation rules for model attributes.
   */
  public function rules()
  {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array (
        array (
            'Descrizione, Transito',
            'length',
            'max' => 250 
        ),
        array (
            'GateID, TimeID',
            'length',
            'max' => 20 
        ),
        array (
            'epoch',
            'safe' 
        ),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array (
            'ID, Descrizione, GateID, TimeID, Transito, epoch',
            'safe',
            'on' => 'search' 
        ) 
    );
  }

  /**
   *
   * @return array relational rules.
   */
  public function relations()
  {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array (
        'gate' => array (
            self::BELONGS_TO,
            'Gate',
            'GateID' 
        ),
        'time' => array (
            self::BELONGS_TO,
            'TimeSchedule',
            'TimeID' 
        ) 
    );
  }

  /**
   *
   * @return array customized attribute labels (name=>label)
   */
  public function myAttributeLabels()
  {
    return array (
        'ID' => 'ID',
        'Descrizione' => t ( 'Description' ),
        'GateID' => t ( 'Gate' ),
        'TimeID' => t ( 'Time Schedule' ),
        'Transito' => t ( 'Mode' ),
        'epoch' => t ( 'Date/Time' ) 
    );
  }

  /**
   * Retrieves a list of models based on the current search/filter conditions.
   * 
   * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
   */
  public function search()
  {
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.
    $criteria = new CDbCriteria ();
    
    $criteria->compare ( 'ID', $this->ID, true );
    $criteria->compare ( 'Descrizione', $this->Descrizione, true );
    $criteria->compare ( 'GateID', $this->GateID, true );
    $criteria->compare ( 'TimeID', $this->TimeID, true );
    $criteria->compare ( 'Transito', $this->Transito, true );
    $criteria->compare ( 'epoch', $this->epoch, true );
    
    return new CActiveDataProvider ( $this, array (
        'criteria' => $criteria 
    ) );
  }

  public function searchForGrid()
  {
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.
    $criteria = new CDbCriteria ();
    
    $criteria->compare ( 'Descrizione', $this->Descrizione, true );
    
    if (! empty ( $this->epoch ))
      $criteria->addCondition ( "epoch LIKE '%$this->epoch%'" );
    
    $transitCondition = self::getSearchForGridConditionForTransitValue ( $this->Transito );
    if (! empty ( $transitCondition ))
      $criteria->addCondition ( $transitCondition );
    
    $gateCondition = self::getSearchForGridConditionForGateValue ( $this->GateID );
    if (! empty ( $gateCondition ))
      $criteria->addCondition ( $gateCondition );
    
    $timeCondition = self::getSearchForGridConditionForTimeValue ( $this->TimeID );
    if (! empty ( $timeCondition ))
      $criteria->addCondition ( $timeCondition );
    
    return new CActiveDataProvider ( $this, array (
        'criteria' => $criteria 
    ) );
  }

  public static function getSearchForGridConditionForTransitValue($label)
  {
    if (empty ( $label ))
      return "";
    
    $free = containsStr ( t ( 'Free access' ), $label );
    $limited = containsStr ( t ( 'Limited access' ), $label );
    
    if (! $free && ! $limited)
      return "Transito='invalid value'";
    
    if ($free && $limited)
      return "";
    
    if ($free)
      return "Transito='" . self::ZTL_TRANSIT_FREE . "'";
    else
      return "Transito='" . self::ZTL_TRANSIT_LIMITED . "'";
  }

  public static function getSearchForGridConditionForTimeValue($label)
  {
    if (empty ( $label ))
      return "";
    
    $ids = array ();
    
    if (containsStr ( t ( 'Always' ), $label ))
      $ids [] = - 1;
    
    foreach ( TimeSchedule::model ()->findAll ( 'Descrizione LIKE :d', array (
        ':d' => '%' . $label . '%' 
    ) ) as $time )
    {
      $ids [] = $time->ID;
    }
    
    if (count ( $ids ) <= 0)
      return "";
    
    return 'TimeID IN (' . implode ( ',', $ids ) . ')';
  }

  public static function getSearchForGridConditionForGateValue($label)
  {
    if (empty ( $label ))
      return "";
    
    $ids = array ();
    
    if (containsStr ( t ( 'All gates' ), $label ))
      $ids [] = - 1;
    
    foreach ( Gate::model ()->findAll ( 'Descrizione LIKE :d', array (
        ':d' => '%' . $label . '%' 
    ) ) as $gate )
    {
      $ids [] = $gate->ID;
    }
    
    if (count ( $ids ) <= 0)
      return "";
    
    return 'GateID IN (' . implode ( ',', $ids ) . ')';
  }

  public function getTransitLabel()
  {
    return $this->isLimited () ? t ( 'Limited access' ) : t ( 'Free access' );
  }

  public function isLimited()
  {
    return $this->Transito == self::ZTL_TRANSIT_LIMITED;
  }

  /**
   *
   * @param string $now          
   * @return ZtlValidityResult
   */
  public function getValidity($now = null)
  {
    $now = DateHelper::ensureObject ( $now );
    $nowEx = DateHelper::ensureObjectEx ( $now );
    
    $result = new ZtlValidityResult ();
    $result->timestamp = $now;
    $result->ztl = $this;
    
    if ($this->TimeID == - 1)
    {
      $result->timeSchedule = null;
      $result->validTimeSlots = array ();
      $result->isValid = true;
      $result->priorityForSchedule = 0;
    }
    else
    {
      $result->timeSchedule = $this->time;
      if ($result->timeSchedule === null)
      {
        $result->isValid = true;
        $result->priorityForSchedule = 0;
      }
      else
      {
        if ($result->timeSchedule->isValidToday ( $now ))
        {
          $result->priorityForSchedule = 1;
          foreach ( $result->timeSchedule->timeSlots as $slot )
          {
            if ($slot->isValidToday ( $now ))
            {
              $result->validTimeSlots [] = $slot;
              $result->priorityForSlot = max ( array (
                  $slot->getPriority (),
                  $result->priorityForSlot 
              ) );
            }
          }
          $result->isValid = count ( $result->validTimeSlots ) > 0;
        }
      }
    }
    
    return $result;
  }

  public function getIconTag($size = 24)
  {
    $htmlOptions = array (
        'width' => $size,
        'height' => $size 
    );
    
    $tagImg = "";
    
    $url = null;
    if (user ()->checkAccess ( 'ztl_edit' ))
      $url = url ( "ztlEditor/" . $this->ID );
    
    if ($this->TimeID == - 1)
    {
      $tagImg = $this->Transito == self::ZTL_TRANSIT_LIMITED ? ImageHelper::getImageTag ( '_red.png', t ( 'Limited access' ) . ': ' . $this->Descrizione, $htmlOptions ) : ImageHelper::getImageTag ( '_green.png', t ( 'Free access' ) . ': ' . $this->Descrizione, $htmlOptions );
      if ($url != null)
        $tagImg = '<a target="_blank" href="' . $url . '">' . $tagImg . '</a>';
    }
    else
    {
      $tagImg = $this->Transito == self::ZTL_TRANSIT_LIMITED ? $this->time->getIconTagFinal ( t ( 'Limited access' ) . ': ' . $this->Descrizione, $size, null, $url ) : $this->time->getIconTagFinal ( t ( 'Free access' ) . ': ' . $this->Descrizione, $size, null, $url );
    }
    
    return $tagImg;
  }

  public function getIconTagForDay($day = null, $size = 24)
  {
    $day = DateHelper::ensureObjectEx ( $day );
    $htmlOptions = array (
        'width' => $size,
        'height' => $size 
    );
    
    $tagImg = "";
    
    $url = null;
    if (user ()->checkAccess ( 'ztl_edit' ))
      $url = url ( "ztlEditor/" . $this->ID );
    
    if ($this->TimeID == - 1)
    {
      $tagImg = $this->Transito == self::ZTL_TRANSIT_LIMITED ? ImageHelper::getImageTag ( '_red.png', t ( 'Limited access' ) . ': ' . $this->Descrizione, $htmlOptions ) : ImageHelper::getImageTag ( '_green.png', t ( 'Free access' ) . ': ' . $this->Descrizione, $htmlOptions );
      if ($url != null)
        $tagImg = '<a target="_blank" href="' . $url . '">' . $tagImg . '</a>';
    }
    else
    {
      $tagImg = $this->Transito == self::ZTL_TRANSIT_LIMITED ? $this->time->getIconTagFinalForDay ( $day, t ( 'Limited access' ) . ': ' . $this->Descrizione, $size, null, $url ) : $this->time->getIconTagFinalForDay ( $day, t ( 'Free access' ) . ': ' . $this->Descrizione, $size, null, $url );
    }
    
    return $tagImg;
  }
}