<?php

class Pampa_Controller_Action extends Zend_Controller_Action {

  /**
   * flash messages
   * @var Zend_Controller_Action_Helper_FlashMessenger
   */
  protected $_flashMessages;

  /**
   * redirector helper
   * @var Zend_Controller_Action_Helper_Redirector
   */
  protected $_redirector;

  public function init() {

    $this->_redirector = $this->getHelper("Redirector");
    $this->_flashMessages = new Pampa_View_Helper_FlashMessages();

    parent::init();
  }

  /**
   * Redireciona para a url de acordo com os parametros
   * @param String $controller
   * @param String $action
   * @param Array $params
   * @param String $module
   */
  protected function langRedirectTo($controller, $action, $params = array(), $module = NULL) {
    $url = $this->getUrlTo(Plugin_Language::getShort()."/".$controller, $action, $params, $module);
    $this->_redirect($url);
  }

  /**
   * Redireciona para a url de acordo com os parametros
   * @param String $controller
   * @param String $action
   * @param Array $params
   * @param String $module
   */
  protected function redirectTo($controller, $action = '', $params = array(), $module = NULL) {
    $url = $this->getUrlTo($controller, $action, $params, $module);
    $this->_redirect($url);
  }

  /**
   * retorna a URL de acordo com os parametros
   * @param String $controller
   * @param String $action
   * @param Array $params
   * @param String|NULL $module
   * @return String
   */
  protected function getUrlTo($controller, $action, $params = NULL, $module = NULL){
    // monta os parametros
    $parameters = "";

    if(!empty($params)){
      foreach($params as $key => $value) {
        $parameters .= $key."/".$value."/";
      }
    }

    $url_parts = array();

    // valida o modulo
    if(empty($module)) {
      // get the default module
      $current_module = $this->_request->getModuleName();

      // get the app config
      $config = Zend_Registry::get("_app_config");
      $default_module = $config->resources->frontController->defaultModule;

      // check if is the default module
      if($current_module != $default_module){
        $url_parts[] = $current_module;
      }

    }

    if(!empty($controller)){
      $url_parts[] = $controller;
    }

    if(!empty($action)){
      $url_parts[] = $action;
    }

    if(!empty($parameters)){
      $url_parts[] = $parameters;
    }

    $url = join("/", $url_parts);
    return BASE_URL.$url;
  }

  /**
   * Cancela o layout e a view e renderiza um json
   * @param $data array para envio no JSON
   * @return void
   */
  protected function renderJson($data) {
    // desabilita a view e o layout
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);

    // echos com o json
    echo Zend_Json::encode($data);
    exit ();
  }

}