<?php

/**
 * This is the model class for table "timetable".
 *
 * The followings are the available columns in table 'timetable':
 * @property string $ID
 * @property string $Descrizione
 * @property string $epoch
 * @property integer $start_day
 * @property integer $start_month
 * @property integer $end_day
 * @property integer $end_month
 * @property string $icon
 * @property TimeSlot[] timeSlots
 * @property boolean $for_run
 * @property boolean $for_whitelisttable
 * @property boolean $for_ztl
 */
class TimeSchedule extends ActiveRecord
{

  /**
   * Returns the static model of the specified AR class.
   *
   * @param string $className
   *          active record class name.
   * @return TimeSchedule 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 'timetable';
  }

  protected function beforeSave()
  {
    $this->epoch = new DateTime ();
    
    return parent::beforeSave ();
  }

  protected function beforeDelete()
  {
    foreach ( $this->timeSlots as $timeSlot )
      $timeSlot->delete ();
    
    return parent::beforeDelete ();
  }

  /**
   *
   * @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 (
            'start_day, start_month, end_day, end_month',
            'numerical',
            'integerOnly' => true 
        ),
        array (
            'Descrizione',
            'length',
            'max' => 250 
        ),
        array (
            'epoch, icon, for_run, for_whitelisttable, for_ztl',
            'safe' 
        ),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array (
            'Descrizione',
            'unique' 
        ),
        array (
            'Descrizione',
            'required' 
        ),
        array (
            'ID, Descrizione, epoch, start_day, start_month, end_day, end_month, icon',
            '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 (
        'timeSlots' => array (
            self::HAS_MANY,
            'TimeSlot',
            'TimeID' 
        ),
        'plateAuthorizations' => array (
            self::HAS_MANY,
            'PlateAuthorization',
            'TimeID' 
        ),
        'ztls' => array (
            self::HAS_MANY,
            'Ztl',
            'TimeID' 
        ),
        'runSchedules' => array (
            self::HAS_MANY,
            'RunSchedule',
            'id_time_table' 
        ) 
    );
  }

  public function behaviors()
  {
    return array (
        'edatetimebehavior' => array (
            'class' => 'ext.EDateTimeBehavior' 
        ) 
    );
  }

  /**
   *
   * @return array customized attribute labels (name=>label)
   */
  public function myAttributeLabels()
  {
    return array (
        'ID' => 'ID',
        'Descrizione' => t ( 'Description' ),
        'epoch' => t ( 'Epoch' ),
        'start_day' => t ( 'Start Day' ),
        'start_month' => t ( 'Start Month' ),
        'end_day' => t ( 'End Day' ),
        'end_month' => t ( 'End Month' ),
        'for_run' => t ( 'Tasks' ),
        'for_whitelisttable' => t ( 'Plate authorizations' ),
        'for_ztl' => t ( 'ZTL' ) 
    );
  }

  /**
   * 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 ( 'epoch', $this->epoch, true );
    $criteria->compare ( 'start_day', $this->start_day );
    $criteria->compare ( 'start_month', $this->start_month );
    $criteria->compare ( 'end_day', $this->end_day );
    $criteria->compare ( 'end_month', $this->end_month );
    
    return new CActiveDataProvider ( $this, array (
        'criteria' => $criteria 
    ) );
  }

  /**
   *
   * @return TimeSchedule[ID]
   */
  public static function getTimeScheduleArray()
  {
    $data = array ();
    foreach ( TimeSchedule::model ()->findAll () as $item )
    {
      $data [$item->ID] = $item->Descrizione;
    }
    return $data;
  }

  /**
   *
   * @return TimeSchedule[ID]
   */
  public static function getTimeScheduleArrayForZtl()
  {
    $data = array ();
    foreach ( TimeSchedule::model ()->findAll ( 'for_ztl=1' ) as $item )
    {
      $data [$item->ID] = $item->Descrizione;
    }
    return $data;
  }

  /**
   *
   * @return TimeSchedule[ID]
   */
  public static function getTimeScheduleArrayForRuns()
  {
    $data = array ();
    foreach ( TimeSchedule::model ()->findAll ( 'for_run=1' ) as $item )
    {
      $data [$item->ID] = $item->Descrizione;
    }
    return $data;
  }

  /**
   *
   * @return TimeSchedule[ID]
   */
  public static function getTimeScheduleArrayForPlateAuths($descriptions = NULL)
  {
    $data = array ();
    
    $attributes = array(
		'for_whitelisttable' => array(1)
    );
    if ($descriptions) {
    	$attributes = array_merge($attributes, array('Descrizione' => $descriptions));
    }
    
    $timeSchedules = TimeSchedule::model ()->findAllByAttributes ($attributes);
    foreach ( $timeSchedules as $timeSchedule )
    {
    	$data [$timeSchedule->ID] = $timeSchedule->Descrizione;
    }
    return $data;
  }

  /**
   * se $now è nelle date del TimeSchedule (non guarda gli slot!)
   *
   * @param mixed $now          
   * @return boolean
   */
  public function isValidToday($now = null)
  {
    $now = DateHelper::ensureObjectEx ( $now );
    
    if ($this->start_month != null && $this->end_month != null && $this->start_day != null && $this->end_day != null && $this->start_month != 0 && $this->end_month != 0 && $this->start_day != 0 && $this->end_day != 0)
    {
      if (in_range ( $now->month, $this->start_month, $this->end_month ) && in_range ( $now->day, $this->start_day, $this->end_day ))
      {
        return true;
      }
      else
      {
        return false;
      }
    }
    else
    {
      return true;
    }
  }

  /**
   * se $now è nelle date del TimeSchedule - guarda gli slot!
   *
   * @param mixed $now          
   * @return TimeSlot
   */
  public function getBestSlotToday($now = null)
  {
    $now = DateHelper::ensureObject ( $now );
    $bestSlot = null;
    if ($this->isValidToday ( $now ))
    {
      foreach ( $this->timeSlots as $slot )
      {
        if ($slot->isValidToday ( $now ))
        {
          if ($bestSlot == null || $bestSlot->getPriority () < $slot->getPriority ())
          {
            $bestSlot = $slot;
          }
        }
      }
    }
    
    return $bestSlot;
  }

  /**
   *
   * @param string $default          
   * @return string
   */
  public function getIconUrl($default = null)
  {
    $i = $this->icon;
    if (! empty ( $i ))
    {
      return Yii::app ()->createAbsoluteUrl ( '/images/time-schedule/' . $i );
    }
    if (! empty ( $default ))
    {
      return Yii::app ()->createAbsoluteUrl ( $default );
    }
    return null;
  }

  /**
   *
   * @param array $params
   *          html parameters
   * @return string html code
   */
  public function getIconTag($params = array(), $url = null)
  {
    $src = $this->getIconUrl ();
    if ($src == null)
      return "";
    $content = HtmlHelper::img ( $src, $params ['alt'], $params );
    ;
    if (empty ( $url ))
    {
      if (user ()->checkAccess ( 'manage_time_schedule' ))
      {
        $url = url ( 'timeSchedule/' . $this->ID );
      }
    }
    if (! empty ( $url ))
      $content = "<a target=\"_blank\" href=\"$url\">$content</a>";
    return $content;
  }

  /**
   * dice se la pianificazione corrisponde sia per timeschedule che per time slot al GIORNO (non l'ora) passata
   *
   * @param string $day          
   * @return boolean
   */
  public function hasSlotsToday($day = null)
  {
    $day = DateHelper::ensureObjectEx ( $day );
    foreach ( $this->timeSlots as $slot )
      if ($slot->isToday ( $day ))
        return true;
    return false;
  }

  /**
   *
   * @param string $description          
   * @param number $size          
   * @return string
   */
  public function getIconTagFinalForDay($day = null, $description = null, $size = 24, $style = null, $url = null)
  {
    $day = DateHelper::ensureObjectEx ( $day );
    if (! $this->isValidToday ( $day ))
      return "";
    if (! $this->hasSlotsToday ( $day ))
      return "";
    if (empty ( $description ))
      $description = $this->Descrizione;
    return $this->getIconTag ( array (
        'style' => $style,
        'witdh' => $size,
        'height' => $size,
        'alt' => $description,
        'title' => $description 
    ), $url );
  }

  /**
   *
   * @param string $description          
   * @param number $size          
   * @return string
   */
  public function getIconTagFinal($description = null, $size = 24, $style = null, $url = null)
  {
    if (empty ( $description ))
      $description = $this->Descrizione;
    return $this->getIconTag ( array (
        'style' => $style,
        'witdh' => $size,
        'height' => $size,
        'alt' => $description,
        'title' => $description 
    ), $url );
  }

  /**
   * dice se l'oggetto è referenziato da almeno una tabella (ztltable, run_schedule, whitelisttable)
   *
   * @return boolean
   */
  public function getIsInUse()
  {
    return array_sum ( $this->getUsingObjectsCount () ) > 0;
  }

  /**
   * restituisce il conteggio degli oggetti che utilizzano questa time schedule
   *
   * @return int[] con indici ztl/wlt/run
   */
  public function getUsingObjectsCount()
  {
    $array = array ();
    $array ['wlt'] = query ( "SELECT count(id) AS cnt FROM whitelisttable WHERE TimeID=:id", array (
        ':id' => $this->ID 
    ) )->cnt;
    $array ['run'] = query ( "SELECT count(id) AS cnt FROM run_schedule WHERE id_time_table=:id", array (
        ':id' => $this->ID 
    ) )->cnt;
    $array ['ztl'] = query ( "SELECT count(id) AS cnt FROM ztltable  WHERE TimeID=:id", array (
        ':id' => $this->ID 
    ) )->cnt;
    return $array;
  }

  /**
   *
   * @return string label con indicato gli utilizzatori di questo oggetto
   */
  public function getUsingObjectsTypes()
  {
    $cnt = $this->getUsingObjectsCount ();
    $using = array ();
    if ($cnt ['ztl'])
      $using [] = t ( "ZTL" ) . " ($cnt[ztl])";
    if ($cnt ['wlt'])
      $using [] = t ( "White lists" ) . " ($cnt[wlt])";
    if ($cnt ['run'])
      $using [] = t ( "Tasks" ) . " ($cnt[run])";
    if (count ( $using ) <= 0)
      $using [] = t ( 'None' );
    return implode ( ', ', $using );
  }
}