<?php
class Project_LabelController extends Library_Controller {
	public function __call($methodName, $args) {
		//zpracovani vstupnich dat
		$objectInfo = $this->_parseActionName($methodName);
		
		//kontorla jestli je format ZIP
		if ($objectInfo["format"] == "zip") {
			//pozadavek na stazeni souboru
			$this->_getLabel($objectInfo);
			return;
		}
		
		//kontrola jestli byl odeslan objekt label
		if (!isset($_REQUEST["label"])) {
			//objekt nebyl odeslal, vypisi se data
			$this->_list($objectInfo);
			return;
		}
		
		//vytvoreni objektu
		$tableProjects = new Application_Model_Projects();
		$response = new Library_Response();
		
		//kontrola dat
		try {
			//kontorla odeslanych dat
			$data = $_REQUEST["label"];
			
			if (!isset($data["label_name"], $data["comment"])) {
				//data nejsou kompletni
				$response->setStatus("DATA_NOT_COMPLETE", 400);
				throw new Zend_Exception("Data sent to server is not complete");
			}
			
			//nacteni projektu
			$project = $tableProjects->find($objectInfo["id"])->current();
			
			if (!$project) {
				//projekt nebyl nalezen
				$response->setStatus("PROJECT_NOT_FOUND", 404);
				throw new Zend_Exception("Project id " . $objectInfo["id"] . " not found");
			}
			
			//nacteni spolupracovniku pro kotnrolu opravneni
			$colabours = $project->findDependentRowset("Application_Model_ProjectsColabours", "project");
			$colabourList = array();
			
			foreach ($colabours as $colabour) {
				$colabourList[] = $colabour->user_id;
			}
			
			//kontrola opravneni
			if ($this->_user->id != $project->user_id && !in_array($this->_user->id, $colabourList) && $this->_user->id != 1 && !in_array("PROJECT_MANAGER", $this->_user->getRoles())) {
				//uzivatel neni opravnen vytvorit obraz
				$response->setStatus("NOT_PERMITED", 403);
				throw new Zend_Exception("User id " . $this->_user->id . " is not permited to create label of project id " . $project->id);
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"], "post");
			return;
		}
		
		//vytvoreni radku
		$tableLabels = new Application_Model_ProjectsLabels();
		$row = $tableLabels->createRow();
		
		$row->label_name = $data["label_name"];
		$row->comment = $data["comment"];
		$row->user_id = $this->_user->id;
		$row->directory_id = $project->directory_id;
		
		$row->save();
		
		//nalezeni hlavniho adredare
		$directory = $project->findParentRow("Application_Model_DocumentsDirectories", "directory");
		
		//nacteni struktury
		$root = new Library_Virtual_Directory($directory);
		$root->loadChildrens();
		
		//vytvoreni zip archivu
		$zipName = tempnam(APPLICATION_PATH . "/../tmp/project/", "project_");
		
		$zip = new ZipArchive();
		$zip->open($zipName, ZipArchive::CREATE);
		
		//prochazeni struktury a zapis dokumentu
		$pathList = array();
		$this->_writeDocuments($root, $zip, $pathList);
		
		//uzavreni ZIP dokumentu a ulozeni do databaze
		$zip->close();
		
		$tableContents = new Application_Model_ProjectsLabelsContents();
		
		$content = $tableContents->createRow();
		$content->label_id = $row->id;
		$content->content = "";
		
		$content->save();
		
		//Zapsani dokumentu
		$content->content = new Zend_Db_Expr("LOAD_FILE('$zipName')");
		$content->save();
		
		//smazani docasneho souboru
		unlink($zipName);
		
		//zapsani dokumentu
		$tablePaths = new Application_Model_ProjectsLabelsDocuments();
		$insert = array(
			"document_uuid" => ""
			, "label_id" => $row->id
			, "paths" => ""
		);
		
		foreach ($pathList as $uuid => $paths) {
			$insert["document_uuid"] = $uuid;
			$insert["paths"] = Zend_Json::encode($paths);
			
			$tablePaths->insert($insert);
		}
		
		//nastaveni odpovedi
		$response->setOk();
		$response["label"] = $row;
		
		$this->view->project_id = $project->directory_id;
		
		$this->_sendToRender($response, $objectInfo["format"], "post");
	}
	
	protected function _list($objectInfo) {
		//priprava dat
		$response = new Library_Response();
		$tableProjects = new Application_Model_Projects();
		
		//kontrola dat
		try {
			//nacteni projektu
			$project = $tableProjects->find($objectInfo["id"])->current();
			
			if (!$project) {
				//projekt nebyl nalezen
				$response->setStatus("PROJECT_NOT_FOUND", 404);
				throw new Zend_Exception("Project id " . $objectInfo["id"] . " not found");
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"], "list");
			return;
		}
		
		//nalezeni labelu
		$labels = $project->findDependentRowset("Application_Model_ProjectsLabels", "project");
		
		//nastaveni a odeslani odpovedi
		$response->setOk();
		$response["label"] = $labels;
		$this->view->project = $project;
		
		$this->_sendToRender($response, $objectInfo["format"], "list");
	}
	
	protected function _writeDocuments(Library_Virtual_Directory $directory, ZipArchive $zip, & $paths) {
		//vytvoreni adredare
		$zip->addEmptyDir($directory->getPath());
		
		//vytvoreni podadredsaru
		$directories = $directory->getDirs();
		
		foreach ($directories as $dir) {
			$this->_writeDocuments($dir, $zip, $paths);
		}
		
		//zapsani dokumentu
		$documents = $directory->getDocuments();
		
		foreach ($documents as $document) {
			$document->addToArchive($zip);
			
			//zapsani do seznamu cest
			if (!isset($paths[$document->getUuid()])) {
				$paths[$document->getUuid()] = array();
			}
			
			$paths[$document->getUuid()] = $document->getPath();
		}
	}
	
	protected function _getLabel($objectInfo) {
		// vypnuti lyoutu a view
		$this->_helper->layout()->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
		//nacteni obsahu labelu
		$tableContents = new Application_Model_ProjectsLabelsContents();
		$content = $tableContents->find($objectInfo["id"]);
		
		if (!$content) {
			$response = new Library_Response();
			$response->setStatus("LABEL_NOT_FOUND", 404);
			echo Zend_Json::encode($response);
			return;
		}
		
		//odeslani hlavicek
		header("Content-Type: application/zip");
		echo $content->content;
	}
}