<?php

/**
 * This is the model class for table "timezonetable".
 *
 * The followings are the available columns in table 'timezonetable':
 * @property string $ID
 * @property string $Descrizione
 * @property string $WeekDay
 * @property string $YearDay
 * @property string $TimeStart
 * @property string $TimeStop
 * @property string $TimeID
 * @property string $epoch
 * @property TimeSchedule $mySchedule
 */
class TimeSlot extends ActiveRecord
{
	
	
	const TS_ALL_DAYS       = 'Tutti i giorni';
	const TS_MONDAY      		= 'Lunedì';
	const TS_TUESDAY  			= 'Martedì';
	const TS_WEDNESDAY      = 'Mercoledì';
	const TS_THURSDAY  			= 'Giovedì';
	const TS_FRIDAY      		= 'Venerdì';
	const TS_SATURDAY  			= 'Sabato';
	const TS_SUNDAY  				= 'Domenica';
	const TS_SINGLE_DAY  		= 'single_day';
	const TS_SPECIAL_DAY  	= 'special_day';

	public $updateType;
	
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return TimeSlot 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 'timezonetable';
	}
	public function beforeSave()
	{
			$dateT = DateTime::createFromFormat(Yii::app()->params['timeselect_format'][Yii::app()->language]['php'], $this->TimeStop);

			$dateT->add(new DateInterval('PT59S'));
			
			$this->TimeStop = $dateT->format('H:i:s');

			
		return parent::beforeSave();
	}
	/**
	 * @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, WeekDay, YearDay', 'length', 'max'=>250),
			array('TimeID', 'length', 'max'=>20),
			array('TimeStart, TimeStop, epoch, dayOfTheYear', 'safe'),
			array('TimeStart, TimeStop', 'required'),
			array('TimeStop', 'compare', 'compareAttribute'=>'TimeStart', 'operator'=> '!='),
				
			array('WeekDay', 'default', 'value'=>self::TS_ALL_DAYS, 'setOnEmpty'=>self::TS_ALL_DAYS),
			array('WeekDay', 'in', 'range'=> array(
					self::TS_ALL_DAYS,
					self::TS_MONDAY,
					self::TS_TUESDAY,
					self::TS_WEDNESDAY,
					self::TS_THURSDAY,
					self::TS_FRIDAY,
					self::TS_SATURDAY,
					self::TS_SUNDAY,
					self::TS_SINGLE_DAY,
					self::TS_SPECIAL_DAY,
			)
			),				
				
				
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('ID, Descrizione, WeekDay, YearDay, TimeStart, TimeStop, TimeID, epoch, dayOfTheYear', '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(
				'mySchedule'	 => array(self::BELONGS_TO, 'TimeSchedule', 'TimeID'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function myAttributeLabels()
	{
		return array(
			'ID' => 'ID',
			'Descrizione' => t('Description'),
			'WeekDay' => t('Type of Day'),
			'YearDay' => t('Date'),
			'TimeStart' => t('Start Time'),
			'TimeStop' => t('End Time'),
			'TimeID' => t('Time Schedule'),
			'epoch' => t('Epoch'),
			'dayOfTheYear' => t('Day Of The Year'),
		);
	}
	
	public function getDayOfTheYear()
	{
		if(empty($this->YearDay))
			return null;
		

		$date = DateTime::createFromFormat('d-m', $this->YearDay);
		
		return $date;
	}
	public function setDayOfTheYear($date)
	{
		if(empty($date))
		{
			$this->YearDay = "";
			return;
		}
		
		$dateT = DateTime::createFromFormat(Yii::app()->params['dayoftheyearselect_format'][Yii::app()->language]['php'], $date);
		
	
		$this->YearDay = $dateT->format('d-m');  
	}
	
	/**
	 * 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('WeekDay',$this->WeekDay,true);
		$criteria->compare('YearDay',$this->YearDay,true);
		$criteria->compare('TimeStart',$this->TimeStart,true);
		$criteria->compare('TimeStop',$this->TimeStop,true);
		$criteria->compare('TimeID',$this->TimeID,true);
		$criteria->compare('epoch',$this->epoch,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * get slot prority
	 * @return number
	 */
	public function getPriority()
	{
	  // tutti i giorni, giorno sett, spec day, data <-
	  
	  if($this->WeekDay == TimeSlot::TS_ALL_DAYS)
	    return 1;
	  
	  if(
	         $this->WeekDay == TimeSlot::TS_MONDAY
	      || $this->WeekDay == TimeSlot::TS_TUESDAY
	      || $this->WeekDay == TimeSlot::TS_WEDNESDAY
	  	  || $this->WeekDay == TimeSlot::TS_THURSDAY
	  	  || $this->WeekDay == TimeSlot::TS_FRIDAY
	  	  || $this->WeekDay == TimeSlot::TS_SATURDAY
	  	  || $this->WeekDay == TimeSlot::TS_SUNDAY
	  )
	    return 2;
	  
	  if($this->WeekDay == TimeSlot::TS_SPECIAL_DAY)
	    return 3;
	  
	  if($this->WeekDay == TimeSlot::TS_SINGLE_DAY)
	    return 4;
	  
	  return 0;
	}
	
	/**
	 * validità sello slot per GIORNO (non per ORA)
	 * @param string $now
	 * @return boolean
	 */
	public function isToday($now=null)
	{
    $now = DateHelper::ensureObject($now);
    $nowEx = new DateTimeEx($now);
    $isToday = false;
     
    if($this->WeekDay == TimeSlot::TS_ALL_DAYS)
      $isToday = true;
     
    if($this->WeekDay == TimeSlot::TS_MONDAY && $now->format('w')==1)
      $isToday = true;
     
    if($this->WeekDay == TimeSlot::TS_TUESDAY && $now->format('w')==2)
      $isToday = true;
     
    if($this->WeekDay == TimeSlot::TS_WEDNESDAY && $now->format('w')==3)
      $isToday = true;
     
    if($this->WeekDay == TimeSlot::TS_THURSDAY && $now->format('w')==4)
      $isToday = true;
     
    if($this->WeekDay == TimeSlot::TS_FRIDAY && $now->format('w')==5)
      $isToday = true;
    
    if($this->WeekDay == TimeSlot::TS_SATURDAY && $now->format('w')==6)
      $isToday = true;
    
    if($this->WeekDay == TimeSlot::TS_SUNDAY && $now->format('w')==0)
      $isToday = true;
    
    if($this->WeekDay == TimeSlot::TS_SPECIAL_DAY)
    {
      foreach(SpecialDay::model()->findAll() as $sd)
      {
        if($sd->month == $now->format('m') && $sd->day == $now->format('d'))
          $isToday = true;
      }
    }
     
    if($this->WeekDay == TimeSlot::TS_SINGLE_DAY)
    {
      $today = $now->format('d').'-'.$now->format('m');
      if($today == $this->YearDay)
        $isToday = true;
    }
    
    return $isToday;
	}
	
	
	/**
	 * validità sello slot per GIORNO e ORA
	 * @return boolean
	 */
	public function isValidToday($now=null)
	{
    $now = DateHelper::ensureObject($now);
    $nowEx = new DateTimeEx($now);
    $isToday = $this->isToday($now);
	  	  
	  if($isToday)
	  {
	    $startTime = DateHelper::formatISO9075Date($now).' '.$this->TimeStart;
	    $endTime   = DateHelper::formatISO9075Date($now).' '.$this->TimeStop;
	    
	    $tmp_st = dt2s($startTime);
	    $tmp_nw = dt2s($now);
	    $tmp_et = dt2s($endTime);
	     
	    if($tmp_nw >= $tmp_st && $tmp_nw <= $tmp_et)
	    {
	      return true;
	    }
	  }
	   
	  return false;
	}
	
	static public function getTypeOfDayList()
	{
		$typeOfDay = array(
												0 => array('value' => TimeSlot::TS_ALL_DAYS,  	'label' => t('All days')),
												1 => array('value' => TimeSlot::TS_MONDAY, 			'label' => t('Monday')),
												2 => array('value' => TimeSlot::TS_TUESDAY, 		'label' => t('Tuesday')),
												3 => array('value' => TimeSlot::TS_WEDNESDAY, 	'label' => t('Wednesday')),
												4 => array('value' => TimeSlot::TS_THURSDAY, 		'label' => t('Thursday')),
												5 => array('value' => TimeSlot::TS_FRIDAY, 			'label' => t('Friday')),
												6 => array('value' => TimeSlot::TS_SATURDAY, 		'label' => t('Saturday')),
												7 => array('value' => TimeSlot::TS_SUNDAY, 			'label' => t('Sunday')),
												8 => array('value' => TimeSlot::TS_SINGLE_DAY,	'label' => t('Date')),
												9 => array('value' => TimeSlot::TS_SPECIAL_DAY, 'label' => t('Special Days')),
		);
		
		return $typeOfDay;
	}
	
	/**
	 * 
	 * @param integer $timeId
	 * @return multitype:TimeSlot
	 */
	public static function getPeriods($timeId)
	{
	  return TimeSlot::model()->findAll('TimeID=:tid',array(':tid'=>$timeId));
	} 
}










