<?php
class DangerousGoodsFromEventStatsQuery
{

  public function getStatsData($params)
  {
    $model = DangerousGoodsFrequencyByCode::model();
    $model->byGate($params['gates']);
    $model = $this->setDateTimeBoundaries($model, $params);

    if(isset($params['splitByGate']))
    {
    	$model->groupByGate();
    	$model->withGates(isset($params['useJoin']));
    } 
    if(isset($params['splitByHour']))
    	$model->groupByHour();

    if(isset($params['descriptions']))
    {
      $model->withDescriptions();
    }
    
    $query = $model->getDbCriteria();
    
    $query->mergeWith(array('group' => 'Kemler'));

    $query = $this->setSelectColumns($query, $params);
    $query = $this->setOrder($query, $params);

    $dataProvider = new CActiveDataProvider('DangerousGoodsFrequencyByCode',
      array('pagination'=>false)
    );

    $dataProvider->criteria = $query;
    return $dataProvider;
  }

  private function setOrder($query, $params)
  {
  	if(isset($params['splitByGate']))
  		$orderColumns[] = 't.Gate ASC';
  	
  	if(isset($params['splitByHour']))  	
  		$orderColumns[] = 'HOUR(StartTime) ASC';
  	
  	$orderColumns[] = 'Counter DESC';
  	 
  	$order = implode(",", $orderColumns);
  	 
  	$query->mergeWith(array('order' => $order));
  	
  	return $query;
  }

  private function setSelectColumns($query, $params)
  {
  	if(isset($params['splitByGate']))
  	{
  		$selectColumns[] = 't.Gate';
  		$selectColumns[] = 'Descrizione';
  	}
  	  	
  	if(isset($params['splitByHour']))
  		$selectColumns[] = 'HOUR(StartTime) as Hour';

  	$selectColumns[] = "CONCAT(substring(t.kemler,1, char_length(t.Kemler)-4),'-',substring(t.kemler,char_length(t.Kemler)-3)) as Kemler";
  	 
    if(isset($params['descriptions']))
    {
      $selectColumns[] = 'adrt.description as ADR';
      $selectColumns[] = 'onut.description as ONU';
    }
    
	$selectColumns[] = "count(*)  as Counter";

    $query->mergeWith(array('select' => $selectColumns));

    return $query;
  }

  private function setDateTimeBoundaries($model, $params)
  {
    if (isset($params['startTimestamp']))
    {
      $startDate = new DateTime();
      $startDate->setTimestamp($params['startTimestamp']);
      $model->startingFromDate($startDate);
    }

    if (isset($params['endTimestamp']))
    {
      $endDate = new DateTime();
      $endDate->setTimestamp($params['endTimestamp']);
      $model->endingAtDate($endDate);
    }

    if (isset($params['startTime']))
    {
    	$startTime = $theStartTime = DateTime::createFromFormat(Yii::app()->params['timeselect_format'][Yii::app()->language]['php'], $params['startTime']);
    	$model->startingFromTime($startTime);
    }
    
    if (isset($params['endTime']))
    {
    	$endTime = $theStartTime = DateTime::createFromFormat(Yii::app()->params['timeselect_format'][Yii::app()->language]['php'], $params['endTime']);
    	$model->endingAtTime($endTime);
    }    
    
    return $model;
  }

}
