<?php

/*
 *
 * Utilities
 *
 */

class Eppe_Controller_Action extends Zend_Controller_Action {

	protected $params;

	/**
	 * @var Rtn_Ajax_Response
	 */
	protected $ajaxResponse;

	/**
	 * Metoda której można użyć do przetwarzania formularzy ajax.
	 * 
	 * @param Eppe_Form $form
	 * @param mixed $viewFile string: plik widoku, który zostanie zwrócony w ajaxResponse->data
	 * 						  array: 'view'=> instancja obiektu Zend_View,
	 * 								 'file'=> nazwa widoku przekazywana do metody render()
	 * @param callable $fncStoreValsAndReturnAjaxResponse Funkcja, która zostanie wywołana w momencie, gdy formularz zostanie poprawnie zwalidowany. Funkcja musi zwracać obiekt Rtn_Ajax_Response!
	 * @param array $initialData Domyślne dane, którymi zostanie wypełniony formularz przy pierwszym wyświetleniu. Parametr opcjonalny.
	 */
	protected function commonAjaxForm(&$form, $viewFile, $fncStoreValsAndReturnAjaxResponse, $initialData = []) {

		/*
		 * 1 form class
		 * 2 store values
		 * 3 view file
		 * 4 on success data/evalJs
		 */

		// default form action
		if (!$form->getAction()) {
			$routeName = Zend_Controller_Front::getInstance()->getRouter()->getCurrentRouteName();
			$formAction = $this->view->url([], $routeName);
			$form->setAction($formAction);
		}

		$ajaxResponse = false;

		if (!empty($_POST) || !empty($_FILES)) {
			$post = $this->_getPost();

			if ($form->isValid($post)) {
				$ajaxResponse = $fncStoreValsAndReturnAjaxResponse($form);
			} else {
				$form->populate($post);
			}
		} else {
			$form->populate($initialData);
		}

		if (is_string($viewFile)) {
			$view = Zend_Layout::startMvc()->getView();
		}

		if (empty($ajaxResponse)) {
			$data = new stdClass();
			$data->form = $form;
			if (is_array($viewFile)) {
				$viewFile['view']->assign((array) $data);
				$this->ajaxResponse->data = $viewFile['view']->render($viewFile['file']);
			} else {
				$this->ajaxResponse->data = $view->partial($viewFile, null, $data);
			}
		} else {
			$this->ajaxResponse = $ajaxResponse;
		}
	}

	public function looksLikeAjaxOrIframe() {
		$looksLikeAjaxOrIframe = false;
		if (strpos($this->getRequest()->getActionName(), 'ajax') === 0) {
			$looksLikeAjaxOrIframe = true;
		}
		return $looksLikeAjaxOrIframe;
	}

	public function postDispatch() {
		if ($this->isAjax) {
			if ($this->_response->isException() && APPLICATION_ENV === 'development') {
				$exc = current($this->_response->getException());

				$msg = '<h1>Exception</h1><strong>' . $exc->getMessage() . '</strong>' .
					'<pre>' . $exc->getTraceAsString() . '</pre>' .
					'<h1>Queries</h1>' .
					Rtn_RB::getQueriesLogAsString();

				$this->ajaxResponse->data = $msg;
			}
			$this->_response->setBody($this->ajaxResponse);
		}
	}

	public function init() {
		$this->_initViewScriptsPath();
		$this->_initDefaultFormAndValidateTranslator();
		$this->_initCustomHeadScriptClass();
		$this->_initCustomHeadStyleClass();
	}

	protected function _initViewScriptsPath() {
		$this->view->setScriptPath(array(
			LIBRARY_PATH . 'Main/' . $this->_request->getModuleName() . '/views/scripts',
			MODULES_PATH . $this->_request->getModuleName() . '/views/scripts'
		));
	}

	/**
	 * Ładowanie plików z klasami JavaScript dla modułów i kontrolerów
	 */
	protected function _initCustomHeadScriptClass() {
		$this->_pushScriptsToHead(
			Rtn_JS_HeadClasses::get($this->_request->getModuleName(), $this->_request->getControllerName())
		);
	}

	protected function _initCustomHeadStyleClass() {
		$this->_pushStylesToHead(
			Rtn_CSS_HeadClasses::get($this->_request->getModuleName(), $this->_request->getControllerName())
		);
	}

	protected function _pushScriptsToHead($scriptsArray) {
		foreach ($scriptsArray as $script) {
			$this->view->headScript()->appendFile($script);
		}
	}

	protected function _pushStylesToHead($stylesArray) {
		foreach ($stylesArray as $style) {
			$this->view->headLink()->appendStylesheet($style);
		}
	}

	/*
	 * Ustawienie tłumaczeń dla translatora
	 */

	protected function _initDefaultFormAndValidateTranslator() {
		$translator = Zend_Registry::get('Zend_Translate_' . Eppe_Localization::getCurrent());

		Zend_Validate_Abstract::setDefaultTranslator($translator);
		Zend_Form::setDefaultTranslator($translator);
	}

	/*
	 *  Blokuje wyświetlanie layoutu dla strony
	 */

	protected function _setLayout($name) {
		$this->_helper->_layout->setLayout($name);
	}

	/*
	 *  Blokuje wyświetlanie layoutu dla strony
	 */

	protected function _disableLayout() {
		$this->_helper->layout->disableLayout();
	}

	/**
	 *  Zmiana layoutu dla strony
	 *  @param string $name nazwa pliku z layoutem bez rozszerzenia (layout.phtml = layout)
	 */
	protected function _changeLayout($name) {
		$this->_helper->_layout->setLayout($name);
	}

	/**
	 * Zmienia wyświetlany widok
	 * @param string $name Nazwa widoku
	 */
	protected function _changeView($name) {
		$this->_helper->viewRenderer->setRender($name);
	}

	/*
	 * Blokuje wyświetlanie layoutu i widoku
	 */

	protected function _disableView() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
	}

	/*
	 * Przekierowuje do poprzedniej strony
	 */

	public final function redirectBack() {
		$this->_redirect($_SERVER['HTTP_REFERER']);
	}

	public function refresh() {
		$this->_redirect($_SERVER['REQUEST_URI']);
	}

	/*
	 * Inicjuje wiadomości
	 */

	protected function _initFlashMessages() {
		$fm = $this->_helper->getHelper('FlashMessenger');
		$this->view->messages = $fm->getMessages();
	}

	/*
	 * Dodaje wiadomość do kolejki wyświetlania. Wiadomość pokazuje się po oświeżenu strony.
	 * Domyślny typ wiadomości to success
	 * @param1 string Treść wiadomości
	 * @param2 string Klasa css dodana do wiadomości (domyślnie success)
	 */

	protected function _addMessage($msg, $class = 'success') {
		$fm = $this->_helper->getHelper('FlashMessenger');
		$fm->addMessage(array($msg, $class));
	}

	/**
	 * Zwraca tablicę $_POST
	 * @return array
	 */
	protected function _getPost($key = null) {
		if (empty($key)) {
			return $this->_request->getPost();
		} else {
			return $this->_request->getPost($key);
		}
	}

	/**
	 * Sprawdza czy zapytanie jest typem POST
	 * @return bool
	 */
	protected function _isPost() {
		return $this->_request->isPost();
	}

	/**
	 * Zwraca obiekt klasy Zend_Session_Namespace o podanej nazawie
	 * @param string $namespaceName nazwa namespace sesji
	 * @param int $maxHops maksymalna liczba przeładowan strony do wygaśniecia sesji
	 * @return object Zend_Session_Namespace
	 */
	protected function _getSession($namespaceName, $maxHops = null) {
		$namespace = new Zend_Session_Namespace($namespaceName);
		if ($maxHops) {
			$namespace->setExpirationHops($maxHops);
		}
		return $namespace;
	}

	protected function _clearSession($namespaceName) {
		$namespace = new Zend_Session_Namespace($namespaceName);
		$namespace->unsetAll();
	}

}
