<?php

class GatesStatusController extends Controller
{
	protected function beforeAction($event)
	{
	  access_denied_check("view_gates_status");
	  return parent::beforeAction($event);
	}
	
  public function actionIndex()
  {
    $gateGroups = GateGroup::getGateGroups();
    $alerts = Alert::model()->last(20)->findAll();
    $violations = Event::model()->last(20)->findAll();
    
    $this->render('index', array('gateGroups' => $gateGroups, 'alerts' => $alerts, 'violations' => $violations));
  }

  public function actionGateGroupSummary()
  {
    $gateGroups = GateGroup::getGateGroups();

    $result = array();

    foreach($gateGroups as $gateGroup)
    {
      $result[$gateGroup->ID]['gateGroup'] = $gateGroup;
      foreach ($gateGroup->gates as $gate)
      {
        $warning = Alert::model()->byGate($gate)->byType('warning')->recently(10800)->count();
        $alarm = Alert::model()->byGate($gate)->byType('alarm')->recently(10800)->count();
        $info = Alert::model()->byGate($gate)->byType('info')->recently(10800)->count();

        $result[$gateGroup->ID]['gates'][$gate->ID]['gate'] = $gate;
        $result[$gateGroup->ID]['gates'][$gate->ID]['alerts'] = array('warning' => $warning, 'alarm' => $alarm, 'info' => $info);
      }
    }
    echo CJSON::encode($result);
    Yii::app()->end();
  }

  public function actionViewGateList()
  {
    $gateGroups = GateGroup::getGateGroups();
    $this->renderPartial('gates/_gateList', array('gateGroups' => $gateGroups));
  }

  public function actionViewAlertsTable($gateId = null, $quantity = 20)
  {
    if (isset($gateId))
    {
      $gate = $this->findModel('Gate', $gateId, 'Gate');
      $alerts = Alert::model()->byGate($gate)->last($quantity)->findAll();
    }
    else
    {
      $gate = null;
      $alerts = Alert::model()->last($quantity)->findAll();
    }
  
  
    $this->renderPartial('alerts/_alertsTable', array('alerts' => $alerts, 'gate' => $gate));
  }

  public function actionViewViolationsTable($gateId = null, $quantity = 20)
  {
    if (isset($gateId))
    {
      $gate = $this->findModel('Gate', $gateId, 'Gate');
      $violations = Event::model()->byGate($gate)->last($quantity)->findAll();
    }
    else
    {
      $gate = null;
      $violations = Event::model()->last($quantity)->findAll();
    }

    $this->renderPartial('violations/_violationsTable', array('violations' => $violations, 'gate' => $gate));
  }
}
