<?php

class GateBehaviorController extends Controller
{

  protected function beforeAction($event)
  {
    access_denied_check ( "gate_behavior_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 displayed
   */
  public function actionView($id)
  {
    $this->render ( 'view', array (
        'model' => $this->loadModel ( $id ) 
    ) );
  }

  public function actionMatrixSwitch()
  {
    $g = array_get ( $_REQUEST, 'g' );
    $b = array_get ( $_REQUEST, 'b' );
    
    $gb = GateBehavior::findGB ( $g, $b );
    if ($gb == null)
    {
      $gb = new GateBehavior ();
      
      $gb->id_behavior = $b;
      $gb->id_gate = $g;
      $gb->epoch = DateTimeEx::nows ();
      $gb->validate = 0;
      $gb->generate_alarm = 0;
      $gb->to_ignore = 1;
      $gb->transfer_from_vt = 0;
      $gb->transfer_from_event = 0;
      $gb->transfer_empty_plates = 0;
      $gb->is_whitelist = 0;
      
      $gb->insert ();
    }
    else
      $gb->delete ();
    
    $this->redirectTo ( 'gateBehavior/matrix' );
  }

  public function actionMatrix()
  {
    access_denied_check ( "gate_behavior_matrix" );
    
    /** @var Behavior[] $behaviors */
    $behaviors = Behavior::model ()->findAll ();
    /** @var Gate[] $gates */
    $gates = Gate::model ()->findAll ();
    
    $matrix = array ();
    foreach ( $gates as $g )
    {
      $matrix [$g->Gate] = array ();
      foreach ( $behaviors as $b )
        $matrix [$g->Gate] [$b->ID] = GateBehavior::findGB ( $g->Gate, $b->ID );
    }
    
    $this->render ( 'matrix', get_defined_vars () );
  }

  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    access_denied_check ( "gate_behavior_create" );
    $model = new GateBehavior ();
    
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    
    if (isset ( $_POST ['GateBehavior'] ))
    {
      $model->attributes = $_POST ['GateBehavior'];
      $clones = $model->getClones ( false );
      if (count ( $clones ) > 0)
      {
        $clone = array_first ( $clones );
        if (user ()->checkAccess ( 'gate_behavior_update' ))
          $model->addError ( null, t ( "This item already exists!" ) . ' - <a href="' . url ( 'gateBehavior/update/' . $clone->ID ) . '">' . t ( 'Update' ) . '</a>' );
        else
          $model->addError ( null, t ( "This item already exists!" ) );
      }
      else if ($model->save ())
        $this->redirect ( array (
            'view',
            'id' => $model->ID 
        ) );
    }
    
    $this->render ( 'create', array (
        'model' => $model 
    ) );
  }

  /**
   * 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 ( "gate_behavior_update" );
    $model = $this->loadModel ( $id );
    
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    
    if (isset ( $_POST ['GateBehavior'] ))
    {
      $model->attributes = $_POST ['GateBehavior'];
      if ($model->save ())
        $this->redirect ( array (
            'view',
            'id' => $model->ID 
        ) );
    }
    
    $this->render ( 'update', array (
        'model' => $model 
    ) );
  }

  /**
   * 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 ( "gate_behavior_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 ( 'GateBehavior/admin' ) );
    /*
     * $dataProvider=new CActiveDataProvider('GateBehavior');
     * $this->render('index',array(
     * 'dataProvider'=>$dataProvider,
     * ));
     */
  }

  /**
   * Manages all models.
   */
  public function actionAdmin()
  {
    $model = new GateBehavior ( 'search' );
    $model->unsetAttributes (); // clear any default values
    if (isset ( $_GET ['GateBehavior'] ))
      $model->attributes = $_GET ['GateBehavior'];
    
    $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 GateBehavior
   */
  public function loadModel($id)
  {
    $model = GateBehavior::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'] === 'gate-behavior-form')
    {
      echo CActiveForm::validate ( $model );
      Yii::app ()->end ();
    }
  }

  protected function switchField($id, $field, $returnUrl)
  {
    // logLine("/// switchField START $id $field");
    if (! user ()->checkAccess ( "gate_behavior_update" ) && ! user ()->checkAccess ( "gate_behavior_switch" ))
      access_denied_check ( null, true );
    $model = $this->loadModel ( $id );
    // logLine("BEFORE $field=".$model->$field);
    $model->$field = $model->$field == 1 ? 0 : 1;
    // logLine("AFTER $field=".$model->$field);
    if (! $model->save ())
    {
      // logLine("save error");
      // logObj($model->getErrors());
    }
    // else
    // logLine("save ok");
    // logLine("/// switchField END $id $field");
    $this->redirect ( empty ( $returnUrl ) ? url ( "gateBehavior/admin" ) : $returnUrl );
  }

  public function actionSwitchValidate($id = null, $returnUrl = null)
  {
    $this->switchField ( $id, "validate", $returnUrl );
  }

  public function actionSwitchToIgnore($id = null, $returnUrl = null)
  {
    $this->switchField ( $id, "to_ignore", $returnUrl );
  }

  public function actionSwitchTransVt($id = null, $returnUrl = null)
  {
    $this->switchField ( $id, "transfer_from_vt", $returnUrl );
  }

  public function actionSwitchTransEv($id = null, $returnUrl = null)
  {
    $this->switchField ( $id, "transfer_from_event", $returnUrl );
  }

  public function actionSwitchTransEp($id = null, $returnUrl = null)
  {
    $this->switchField ( $id, "transfer_empty_plates", $returnUrl );
  }

  public function actionSwitchIsWhitelist($id = null, $returnUrl = null)
  {
    $this->switchField ( $id, "is_whitelist", $returnUrl );
  }

  public function actionSwitchGenerateAlarm($id, $value, $returnUrl = null)
  {
    if (! user ()->checkAccess ( "gate_behavior_update" ) && ! user ()->checkAccess ( "gate_behavior_switch" ))
      access_denied_check ( null, true );
    $model = $this->loadModel ( $id );
    $model->generate_alarm = $value;
    if (! $model->save ())
    {
      // logLine("save error");
      // logObj($model->getErrors());
    }
    $this->redirect ( empty ( $returnUrl ) ? url ( "gateBehavior/admin" ) : $returnUrl );
  }
}
