<?php

class SectionController extends Controller
{

  protected function beforeAction($event)
  {
    access_denied_check ( "section_management" );
    return parent::beforeAction ( $event );
  }

  /**
   *
   * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
   *      using two-column layout. See 'protected/views/layouts/column2.php'.
   */
  public $layout = '//layouts/column2';

  /**
   * Displays a particular model.
   *
   * @param integer $id
   *          the ID of the model to be displayedSectionController.php
   */
  public function actionView($id)
  {
    $this->render ( 'view', array (
        'model' => $this->loadModel ( $id ) 
    ) );
  }

  /**
   * Displays a particular model.
   *
   * @param integer $id
   *          the ID of the model to be displayed
   */
  public function actionMatrix()
  {
    access_denied_check ( "section_matrix" );
    
    $this->render ( 'matrix' );
  }

  public function actionCreateFast($from, $to)
  {
    access_denied_check ( "section_create" );
    
    $model = new Section ();
    $model->filter_gate_start = 0;
    $model->filter_gate_end = 0;
    $model->description = "$from => $to";
    $model->discard_delta = 0;
    $model->enabled = 0;
    $model->epoch = DateTimeEx::now ();
    $model->final_discard_delta = 0;
    $model->id_gate_end = $to;
    $model->id_gate_start = $from;
    $model->last_event_id = 0;
    $model->last_event_time = DateTimeEx::now ();
    $model->name = "$from => $to";
    $model->road_length = 0;
    $model->road_speed_limit = 0;
    $model->road_speed_limit_unit = 0;
    $model->road_speed_threshold = 0;
    
    $model->insert ();
    
    $this->redirectTo ( 'section/matrix' );
  }

  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    access_denied_check ( "section_create" );
    
    $model = new Section ();
    $model->filter_gate_start = 0;
    $model->filter_gate_end = 0;
    
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    
    if (isset ( $_POST ['Section'] ))
    {
      $inputLimits = null;
      try
      {
        $inputLimits = $this->getInputLimits ();
      }
      catch ( Exception $e )
      {
        $inputLimits = null;
      }
      
      if ($inputLimits !== null)
      {
        $model->attributes = $_POST ['Section'];
        if ($model->save ())
        {
          foreach ( $model->limits as $limitObj )
            $limitObj->delete ();
          
          foreach ( $inputLimits as $limitObj )
          {
            $limitObj->section = $model->id;
            $limitObj->save ();
          }
          
          $this->redirect ( array (
              'view',
              'id' => $model->id 
          ) );
        }
      }
    }
    
    $classLimit = array ();
    $classThreshold = array ();
    
    foreach ( $model->limits as $limitObj )
    {
      $classLimit [$limitObj->class] = $limitObj->road_speed_limit;
      $classThreshold [$limitObj->class] = $limitObj->road_speed_threshold;
    }
    
    foreach ( array_ensure ( array_get ( $_REQUEST, 'ClassLimit', array () ) ) as $class => $limit )
      $classLimit [$class] = $limit;
    
    foreach ( array_ensure ( array_get ( $_REQUEST, 'ClassThreshold', array () ) ) as $class => $limit )
      $classThreshold [$class] = $limit;
    
    $this->render ( 'create', array (
        'model' => $model,
        'classLimit' => $classLimit,
        'classThreshold' => $classThreshold 
    ) );
  }

  public function actionSwitchEnabled($id = null, $returnUrl = null)
  {
    access_denied_check ( "section_update" );
    $model = $this->loadModel ( $id );
    $model->enabled = $model->enabled == 1 ? 0 : 1;
    $model->save ();
    $this->redirect ( empty ( $returnUrl ) ? url ( "section/admin" ) : $returnUrl );
  }

  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   *
   * @param integer $id
   *          the ID of the model to be updated
   */
  public function actionUpdate($id)
  {
    access_denied_check ( "section_update" );
    
    $model = $this->loadModel ( $id );
    
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    
    if (isset ( $_POST ['Section'] ))
    {
      $inputLimits = null;
      try
      {
        $inputLimits = $this->getInputLimits ();
      }
      catch ( Exception $e )
      {
        $inputLimits = null;
      }
      
      if ($inputLimits !== null)
      {
        $model->attributes = $_POST ['Section'];
        if ($model->save ())
        {
          foreach ( $model->limits as $limitObj )
            $limitObj->delete ();
          
          foreach ( $inputLimits as $limitObj )
          {
            $limitObj->section = $model->id;
            $limitObj->save ();
          }
          
          $this->redirect ( array (
              'view',
              'id' => $model->id 
          ) );
        }
      }
    }
    
    $classLimit = array ();
    $classThreshold = array ();
    
    foreach ( $model->limits as $limitObj )
    {
      $classLimit [$limitObj->class] = $limitObj->road_speed_limit;
      $classThreshold [$limitObj->class] = $limitObj->road_speed_threshold;
    }
    
    foreach ( array_ensure ( array_get ( $_REQUEST, 'ClassLimit', array () ) ) as $class => $limit )
      $classLimit [$class] = $limit;
    
    foreach ( array_ensure ( array_get ( $_REQUEST, 'ClassThreshold', array () ) ) as $class => $limit )
      $classThreshold [$class] = $limit;
    
    $this->render ( 'update', array (
        'model' => $model,
        'classLimit' => $classLimit,
        'classThreshold' => $classThreshold 
    ) );
  }

  /**
   *
   * @return SectionLimits[]
   */
  protected function getInputLimits()
  {
    $limits = array ();
    
    $ClassLimit = array_get ( $_REQUEST, 'ClassLimit', array () );
    $ClassThreshold = array_get ( $_REQUEST, 'ClassThreshold', array () );
    
    $Classes = array_keys ( $ClassLimit ) + array_keys ( $ClassThreshold );
    foreach ( $Classes as $class )
    {
      $limit = doubleval ( array_get ( $ClassLimit, $class, 0.0 ) );
      $threshold = doubleval ( array_get ( $ClassThreshold, $class, 0.0 ) );
      if ($limit > 0.0 && $threshold > 0.0)
      {
        $limitObj = new SectionLimits ();
        $limitObj->section = $model->id;
        $limitObj->class = $class;
        $limitObj->road_speed_limit = $limit;
        $limitObj->road_speed_threshold = $threshold;
        $limitObj->epoch = DateTimeEx::nows ();
        $limits [] = $limitObj;
      }
    }
    
    return $limits;
  }

  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   *
   * @param integer $id
   *          the ID of the model to be deleted
   */
  public function actionDelete($id)
  {
    access_denied_check ( "section_delete" );
    
    if (Yii::app ()->request->isPostRequest)
    {
      // we only allow deletion via POST request
      $this->loadModel ( $id )
        ->delete ();
      
      // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
      if (! isset ( $_GET ['ajax'] ))
        $this->redirect ( isset ( $_POST ['returnUrl'] ) ? $_POST ['returnUrl'] : array (
            'admin' 
        ) );
    }
    else
      throw new CHttpException ( 400, 'Invalid request. Please do not repeat this request again.' );
  }

  /**
   * Lists all models.
   */
  public function actionIndex()
  {
    $this->redirect ( url ( "section/admin" ) );
    /*
     * $dataProvider=new CActiveDataProvider('Section');
     * $this->render('index',array(
     * 'dataProvider'=>$dataProvider,
     * ));
     */
  }

  /**
   * Manages all models.
   */
  public function actionAdmin()
  {
    $model = new Section ( 'search' );
    $model->unsetAttributes (); // clear any default values
    if (isset ( $_GET ['Section'] ))
      $model->attributes = $_GET ['Section'];
    
    $this->render ( 'admin', array (
        'model' => $model 
    ) );
  }

  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   *
   * @param
   *          integer the ID of the model to be loaded
   * @return Section
   */
  public function loadModel($id)
  {
    $model = Section::model ()->findByPk ( $id );
    if ($model === null)
      throw new CHttpException ( 404, 'The requested page does not exist.' );
    return $model;
  }

  /**
   * Performs the AJAX validation.
   *
   * @param
   *          CModel the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if (isset ( $_POST ['ajax'] ) && $_POST ['ajax'] === 'section-form')
    {
      echo CActiveForm::validate ( $model );
      Yii::app ()->end ();
    }
  }
}
