<?php
namespace Modules\Documents\Generate\OpenDocument;

class Controller extends \App\Mvc\ControllerAbstract
{
	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['view'] =         ['checkSection' => false,];
		$this->actionsCfg['download'] =     ['checkSection' => false,];
		$this->actionsCfg['print'] =    	['checkSection' => false,];
	}

	/**
	 * Download document
	 * @param Array $R
	 * @return \Engine\Mvc\Response\FileDownload
	 */
	public function actionDownload($R)
	{
		// validate input
		if (!$R['idDocument']) {
			throw new \Engine\Mvc\ControllerException("The parameter `idDocument` is not set");
		}

		\DB::startTransaction();
		try {

			$documentEntity = \Entity\Document::openDocument($R['idDocument']);
			$documentEntity->action = 'download';
			$documentEntity->save();

			\DB::commitTransaction();

			// check if is the original document
			$documentDetails = $this->getFileDetails($R['idDocument']);
			$response = new \Engine\Mvc\Response\FileDownload($documentDetails['fileContent']);
			$response->setFilename($documentDetails['fileName']);

			return $response;
		}
		catch (\App\Entity\Exception $ex) {
			\DB::rollbackTransaction();

			$viewIndex = new View_Index($this);
			$viewIndex->getMessagesCollector()->appendMessages($ex->getMessagesCollector());

			return new \Engine\Mvc\Response\Html($viewIndex->render());
		}

		return NULL;

	}

	/**
	 * View document
	 * @param array $R
	 * @throws \Engine\Mvc\ControllerException
	 * @return \Engine\Mvc\Response\FileView
	 */
	public function actionView($R)
	{
		// validate input
		if (!$R['idDocument']) {
			throw new \Engine\Mvc\ControllerException("The parameter `idDocument` is not set");
		}

		\DB::startTransaction();
		try {

			$documentEntity = \Entity\Document::openDocument($R['idDocument']);
			if ($R['documentAction']) {
				$action = $R['documentAction'];
			}
			else {
				$action = 'view';
			}
			$documentEntity->action = $action;
			$documentEntity->save();

			\DB::commitTransaction();

			// check if is the original document
			$documentDetails = $this->getFileDetails($R['idDocument']);

			$response = new \Engine\Mvc\Response\FileView($documentDetails['fileContent']);
			$response->setFilename($documentDetails['fileName']);
			$response->setFiletype(\Engine\File::getExtension($documentDetails['fileName']));
			return $response;

		}
		catch (\App\Entity\Exception $ex) {
			\DB::rollbackTransaction();

			$viewIndex = new View_Index($this);
			$viewIndex->getMessagesCollector()->appendMessages($ex->getMessagesCollector());

			return new \Engine\Mvc\Response\Html($viewIndex->render());
		}

		return NULL;
	}

	/**
	 * Print document
	 * @param Array $R
	 * @throws \Engine\Mvc\ControllerException
	 * @return \Engine\Mvc\Response\FileView|\Engine\Mvc\Response\Html
	 */
	public function actionPrint($R)
	{
		// validate input
		if (!$R['idDocument']) {
			throw new \Engine\Mvc\ControllerException("The parameter `idDocument` is not set");
		}

		$documentDetails = $this->getFileDetails($R['idDocument']);
		$filetype = \Engine\File::getExtension($documentDetails['fileName']);

		// for non-html documents - load the view action
		if ($filetype!='html') {
			$R['documentAction'] = 'print';
			return $this->actionView($R);
		}

		\DB::startTransaction();
		try {

			$documentEntity = \Entity\Document::openDocument($R['idDocument']);
			$documentEntity->action = 'print';
			$documentEntity->save();

			\DB::commitTransaction();

			$documentDetails = $this->getFileDetails($R['idDocument']);

			$view = new View_Print($this);
			$view->addInput('documentDetails', $documentDetails);
			return new \Engine\Mvc\Response\Html($view->render());
		}
		catch (\App\Entity\Exception $ex) {
			\DB::rollbackTransaction();

			$viewIndex = new View_Index($this);
			$viewIndex->getMessagesCollector()->appendMessages($ex->getMessagesCollector());

			return new \Engine\Mvc\Response\Html($viewIndex->render());
		}

		return NULL;

	}

	/**
	 * Get document file details
	 * @param String $idDocument
	 * @return Array
	 */
	private function getFileDetails($idDocument)
	{
		$details = [
			'fileName' => 			NULL,
			'fileContent' => 		NULL,
		];

		$model = new \Modules\Documents\Generate\OpenDocument\Model();
		$details['fileContent'] = 		$model->getFileContent($idDocument);
		$details['fileName'] = 			$model->getFileName($idDocument);

		return $details;
	}

	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\ControllerAbstract::verifyAccessToAction()
	 */
	protected function verifyAccessToAction($action, $R)
	{
		parent::verifyAccessToAction($action, $R);

		$documentEntity = \Entity\Document::select($R['idDocument']);
		$pivotDocumentObject = new \Modules\Documents\Generate\DocumentPivot($documentEntity->pivotCode, $documentEntity->idPivot);
		if (!$pivotDocumentObject->userHasAccessToGenerate()) {
			throw new \Engine\Mvc\ControllerException(sprintf("You do not have access to the module '%s'", $this->module), "auth_noSectionAccess");
		}
	}
}