<?php

class DiagnosticController extends Controller
{

  public function filters()
  {
    return array(
        'postOnly + update',
        array('application.filters.SyslogFilter - summary',),
    );
  }

  protected function beforeAction($event)
  {
    access_denied_check("diagnostic");
    return parent::beforeAction($event);
  }
  
  public function actionIndex(array $types = null, array $gates = null)
  {
    $criteria=new CDbCriteria();
    $criteria->order = 't.epoch DESC';

    $withCriteria =  array(
            'takenInChargeOperator',
            'managedByOperator',
      	  );
    
    $criteria->with = $withCriteria;
    $criteria->together = true;

    if($types != null)
    {
      if(!is_array($types))
        $types = array($types);
      $criteria->addInCondition("t.type", $types);
    }

    if($gates != null)
    {
    	if(!is_array($gates))
    		$types = array($gates);
    	$criteria->addInCondition("t.gate", $gates);
    }
    
    
    $dataProvider=new CActiveDataProvider('Diagnostic', array(
      'criteria'=>$criteria,

      'pagination'=>array(
          'pageSize'=>20,
      ),
    ));
    
    $gateList = Gate::getAllGates();

    if (Yii::app()->request->isAjaxRequest)
      $this->renderPartial('_diagnosticTable', array('dataProvider' => $dataProvider));
    else
      $this->render('index', array('dataProvider' => $dataProvider, 'types' => $types, 'gateList' => $gateList, 'selectedGates' =>$gates));
  }
  
  public function actionSearch(array $types = null, array $gates = null)
  {
  	$model = new AlertSearchForm();
  	
  	if(isset($types) || isset($gates))
  	{
	  	if(isset($types))
	  		$model->types = $types;
	  	
	  	if($gates)
	  		$model->gates = $gates;
  	} 
  	else if (isset($_GET['DiagnosticSearchForm'])) {
  		//$model->attributes = $_GET['AlertSearchForm'];
  		$model->setAttributes($_POST['DiagnosticSearchForm'], false);
  	}
  	else if (isset($_POST['DiagnosticSearchForm'])) {
  		$model->setAttributes($_POST['DiagnosticSearchForm'], false);
  	} 	
  	
  	
  	$diagnostic = new Diagnostic();
  	
  	if(!empty($model->description))
  		$diagnostic->byDescription($model->description);

  	if(!empty($model->gates))
  		$diagnostic->byGate($model->gates);
  	  	
  	if(!empty($model->types))
  		$diagnostic->byType($model->types);
  	
  	if(isset($model->takenInChargeBy) && $model->takenInChargeBy > 0)
  		$diagnostic->takenInChargeBy(Yii::app()->user->model);
  	
  	if(isset($model->closedBy) && $model->closedBy > 0)
  		$diagnostic->managedBy(Yii::app()->user->model);
  	
  	if(!empty($model->startDateTime))
  	{
  		$theStartTime = DateTime::createFromFormat(Yii::app()->params['datetimeselect_format'][Yii::app()->language]['php'], $model->startDateTime);
  		$diagnostic->after($theStartTime);
  	}
  	
  	if(!empty($model->endDateTime))
  	{
  		$theEndTime = DateTime::createFromFormat(Yii::app()->params['datetimeselect_format'][Yii::app()->language]['php'], $model->endDateTime);
  		$diagnostic->before($theEndTime);
  	}
  	
  	$diagnostic->youngerToOlder();
  	
  	if($_POST['exportbtn'] == 'export')
  	{
  	    $dataProvider = $diagnostic->searchForCsv();

  	    $csv = new ECSVExport($dataProvider);

  	  	$content = $csv->toCSV();
		
  	    $nowDateTime = new DateTime();
      	 
  	    $fileName = "Diagnostics_".$nowDateTime->format("Y_m_d_H_i_s").".csv";
  	
      	Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);
			
		exit();
  	}
  	
  	$dataProvider = $diagnostic->search();
  	
  	$gateList = Gate::getAllGates();
  	  	
 	$this->render('index', array('model' => $model, 'dataProvider' => $dataProvider, 'gateList' => $gateList));
  }
  

  public function actionTakeCharge($id)
  {
    $diagnostic = $this->loadModel($id);
    $operator = Yii::app()->user->model;
    $diagnostic->takeCharge($operator);

    Yii::app()->user->setFlash('success', t('Successfully taken in charge'));

    if (Yii::app()->request->isAjaxRequest)
      $this->renderPartial('_diagnosticRow', array('diagnostic' => new DiagnosticPresenter($diagnostic)));
    else
      $this->redirect(array('/diagnostic/view', 'id' => $id));
  }

  public function actionUpdate($id)
  {
    $diagnostic = $this->loadModel($id);
    $diagnostic->attributes = $_POST['Diagnostic'];

    
    if (!$diagnostic->isManaged())
      $diagnostic->manage(Yii::app()->user->model);

    $diagnostic->save();
 
    Yii::app()->end();
  }

  public function actionManage($id)
  {
    $diagnostic = $this->loadModel($id);

    if($diagnostic->isManaged())
    {

    }
    $operator = Yii::app()->user->model;
    $diagnostic->Manage($operator);

    $this->renderPartial('_diagnosticRow', array('diagnostic' => new DiagnosticPresenter($diagnostic)));
  }

  public function actionReleaseCharge($id)
  {
    $diagnostic = $this->loadModel($id);
    $operator = Yii::app()->user->model;
    $diagnostic->releaseCharge($operator);

    $this->renderPartial('_diagnosticRow', array('$diagnostic' => new DiagnosticPresenter($diagnostic)));
  }

  public function loadModel($id)
  {
    $model = Diagnostic::model()->findByPk($id);
    if($model === null)
      throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
    return $model;
  }
}
