<?php
class BookmarkController extends Controller
{
  protected function findObject($id,$type)
  {
    switch($type)
    {
      case Bookmark::TYPE_ALERT:
        $type = "Alert";
        break;
      case Bookmark::TYPE_EVENT:
        $type = "Event";
        break;
      case Bookmark::TYPE_VEHICLE_TRACE:
        $type = "VehicleTrace";
        break;
      default:
        $type = null;
    }
    if($type!=null)
    {
      return ActiveRecord::model($type)->findByPk($id);
    }
    return null;
  }

  public function actionAdd($id_reference, $type)
  {
    $model = $this->findObject($id_reference, $type);

    $data = $model->getBookmarkData();

    if($data->has_alert && !$data->alert_book)
    {
      $bmark = new Bookmark;
      $bmark->addBookmark(Yii::app()->user, $data->alert_id, Bookmark::TYPE_ALERT);
    }

    if($data->has_event && !$data->event_book)
    {
      $bmark = new Bookmark;
      $bmark->addBookmark(Yii::app()->user, $data->event_id, Bookmark::TYPE_EVENT);
    }

    if($data->has_trace && !$data->trace_book)
    {
      $bmark = new Bookmark;
      $bmark->addBookmark(Yii::app()->user, $data->trace_id, Bookmark::TYPE_VEHICLE_TRACE);
    }

    return "ok";

    Yii::app()->end();
  }

  public function actionRemove($id_reference, $type)
  {
    $model = $this->findObject($id_reference, $type);

    $data = $model->getBookmarkData();

    if($data->has_alert && $data->alert_book)
    {
      Bookmark::model()->byUser(Yii::app()->user)->byIdReference($data->alert_id)->byType(Bookmark::TYPE_ALERT)->deleteRecords();
    }

    if($data->has_event && $data->event_book)
    {
      Bookmark::model()->byUser(Yii::app()->user)->byIdReference($data->event_id)->byType(Bookmark::TYPE_EVENT)->deleteRecords();
    }

    if($data->has_trace && $data->trace_book)
    {
      Bookmark::model()->byUser(Yii::app()->user)->byIdReference($data->trace_id)->byType(Bookmark::TYPE_VEHICLE_TRACE)->deleteRecords();
    }

    return "ok";

    Yii::app()->end();
  }
}