<?php

/**
 * This is the model class for table "diagnostic".
 *
 * The followings are the available columns in table 'diagnostic':
 * @property string $id
 * @property string $uuid
 * @property string $type
 * @property string $sub_type
 * @property string $description
 * @property string $full_desciption
 * @property string $status
 * @property string $action
 * @property string $comment
 * @property string $taken_in_charge_by
 * @property string $taken_in_charge_time
 * @property string $managed_by
 * @property string $managed_time
 * @property string $gate
 * @property string $epoch
 * @property string $note
 * @property string $extra_data
 * @property string $event_time
 */
class Diagnostic extends ActiveRecord
{
	const STATUS_NEW             = "new";
	const STATUS_TAKEN_IN_CHARGE = "taken_in_charge";
	const STATUS_MANAGED         = "managed";
	
	const TYPE_ALARM            = "alarm";
	const TYPE_WARNING          = "warning";
	const TYPE_INFO             = "info";
	
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Diagnosti 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 'diagnostic';
	}

	/**
	 * @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('uuid, type, sub_type, description, status, extra_data', 'length', 'max'=>250),
			array('taken_in_charge_by, managed_by, gate', 'length', 'max'=>20),
			array('full_desciption, action, comment, taken_in_charge_time, managed_time, epoch, note, event_time', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, uuid, type, sub_type, description, full_desciption, status, action, comment, taken_in_charge_by, taken_in_charge_time, managed_by, managed_time, gate, epoch, note, extra_data, event_time', 'safe', 'on'=>'search'),
		);
	}
	public function behaviors()
	{
		return array('edatetimebehavior' => array('class' => 'ext.EDateTimeBehavior'));
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		return array(
				'takenInChargeOperator' => array(self::BELONGS_TO,  'User'     ,  'taken_in_charge_by'),
				'managedByOperator'     => array(self::BELONGS_TO,  'User'     ,  'managed_by'),
				'myGate'    							=> array(self::BELONGS_TO , 'Gate' , array('gate'      => 'Gate')),
		);
	}


	public function takeCharge($operator)
	{
		$this->taken_in_charge_by = $operator->id;
		$timeNow = new DateTime();
		$this->taken_in_charge_time = $timeNow;
		$this->status = self::STATUS_TAKEN_IN_CHARGE;
	
		return $this->save();
	}
	
	public function releaseCharge()
	{
		$this->taken_in_charge_by = null;
		$this->status = self::STATUS_NEW;
	
		return $this->save();
	}
	
	public function manage($operator)
	{
		$this->managed_by = $operator->id;
		$timeNow = new DateTime();
		$this->managed_time = $timeNow;
		$this->status = self::STATUS_MANAGED;
	
		return $this->save();
	}	
	
	
	
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function myAttributeLabels()
	{
		return array(
			'id' => 'ID',
			'uuid' => 'Uuid',
			'type' => 'Type',
			'sub_type' => 'Sub Type',
			'description' => 'Description',
			'full_desciption' => 'Full Desciption',
			'status' => 'Status',
			'action' => 'Action',
			'comment' => 'Comment',
			'taken_in_charge_by' => 'Taken In Charge By',
			'taken_in_charge_time' => 'Taken In Charge Time',
			'managed_by' => 'Managed By',
			'managed_time' => 'Managed Time',
			'gate' => 'Gate',
			'epoch' => 'Epoch',
			'note' => 'Note',
			'extra_data' => 'Extra Data',
			'event_time' => 'Event Time',
		);
	}
	
	public function getGateLabel()
	{
		if ($this->myGate == null)
			return null;
		 
		return  $this->myGate->Descrizione;
	}
	public function getGateShortLabel()
	{
		if ($this->myGate == null)
			return null;
	
		return  $this->myGate->short_name;
	}
	public function after($Time)
	{
		$this->getDbCriteria()->mergeWith(
				array(
						'condition' => 'epoch >= :theStartDateTime',
						'params' => array(':theStartDateTime' => DateHelper::formatISO9075DateTime($Time))
				)
		);
		 
		return $this;
	}
	
	public function before($Time)
	{
		$this->getDbCriteria()->mergeWith(
				array(
						'condition' => 'epoch <= :theEndDateTime',
						'params' => array(':theEndDateTime' => DateHelper::formatISO9075DateTime($Time))
				)
		);
	
		return $this;
	}
	public function isTakenInCharge()
	{
		return ($this->status == self::STATUS_TAKEN_IN_CHARGE);
	}
	
	public function isManaged()
	{
		return ($this->status == self::STATUS_MANAGED);
	}
	
	public function isNew()
	{
		return ($this->status == self::STATUS_NEW);
	}
	public function youngerToOlder()
	{
		$this->getDbCriteria()->order = 't.epoch DESC';
		return $this;
	}
	public function olderToYounger()
	{
		$this->getDbCriteria()->order = 't.epoch ASC';
		return $this;
	}

	public function groupByType()
	{
		$this->getDbCriteria()->group = 't.type';
	
		return $this;
	}
	
	public function byGate($gate)
	{
		if(is_object($gate))
		{
			$className = get_class($gate);
			if(!empty($className) == "Gate")
				$gate = $gate->Gate;
		}
		 
		if(!is_array($gate))
			$gate = array($gate);
		 
		$this->getDbCriteria()->addInCondition('gate', $gate);
		 
		return $this;
	}
	
	public function byType($type)
	{
		if(!is_array($type))
			$type = array($type);
	
		$this->getDbCriteria()->addInCondition('t.type', $type);
	
		return $this;
	}
	
	public function byDescription($description)
	{
		if(!is_array($description))
			$gates = array($description);
	
		$this->getDbCriteria()->addInCondition('description', $description);
	
		return $this;
	}	
	public function takenInChargeBy($operator)
	{
		$this->getDbCriteria()->mergeWith(
				array(
						'condition' => 'taken_in_charge_by >= :takeninchargeby',
						'params' => array(':takeninchargeby' => $operator->id)
				)
		);
		return $this;
	}
	
	public function managedBy($operator)
	{
		$this->getDbCriteria()->mergeWith(
				array(
						'condition' => 'managed_by >= :managedby',
						'params' => array(':managedby' => $operator->id)
				)
		);
		return $this;
	}
	/**
	 * 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('uuid',$this->uuid,true);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('sub_type',$this->sub_type,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('full_desciption',$this->full_desciption,true);
		$criteria->compare('status',$this->status,true);
		$criteria->compare('action',$this->action,true);
		$criteria->compare('comment',$this->comment,true);
		$criteria->compare('taken_in_charge_by',$this->taken_in_charge_by,true);
		$criteria->compare('taken_in_charge_time',$this->taken_in_charge_time,true);
		$criteria->compare('managed_by',$this->managed_by,true);
		$criteria->compare('managed_time',$this->managed_time,true);
		$criteria->compare('gate',$this->gate,true);
		$criteria->compare('epoch',$this->epoch,true);
		$criteria->compare('note',$this->note,true);
		$criteria->compare('extra_data',$this->extra_data,true);
		$criteria->compare('event_time',$this->event_time,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	public function searchForCsv()
	{
	  $crit = clone $this->dbCriteria;
	  
	  $crit->alias = "d";
	  $crit->join='LEFT JOIN gatetable g ON g.gate=d.gate';
	  $crit->select = array(
	      'd.type as '.Yii::t('app', 'Type')
	      ,
	      'd.full_desciption as '.Yii::t('app', 'Description')
	      ,
	      'g.Descrizione as '.Yii::t('app', 'Gate')
	      ,
	      'DATE(d.event_time) as '.Yii::t('app', 'Date')
	      ,
    	  'TIME(d.event_time) as '.Yii::t('app', 'Time')
	      
	  );
	  $crit->order = 'd.event_time DESC';
	  
	  return new CActiveDataProvider($this, array('criteria'=>$crit));
	}
}