<?php
class Project_GetController extends Library_Controller {
	public function __call($methodName, $args) {
		//vyhodnoceni formatu
		$objectInfo = $this->_parseActionName($methodName);
		
		if ($objectInfo["format"] == "zip") {
			//jedna se o pozadavek na zabaleny projekt
			$this->_sendArchive($objectInfo);
			return;
		} elseif ($objectInfo["id"] == "list") {
			//dotaz na vypis
			$this->_list($objectInfo);
			return;
		}
		
		//dokonceni inicializace
		$tableProjects = new Application_Model_Projects;
		$response = new Library_Response();
		
		//nactnei informaci o projektu
		try {
			$project = $tableProjects->find($objectInfo["id"])->current();
			
			if (!$project) {
				//projekt nebyl nalezen
				$response->setStatus("NOT_FOUND", 404);
				throw new Zend_Exception("Project id " . $objectInfo["id"] . " not found");
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"], "get");
			return;
		}
		
		//nacteni spolupracovniku a labelu
		$labels = $project->findDependentRowset("Application_Model_ProjectsLabels", "project");
		$colabours = $project->findDependentRowset("Application_Model_ProjectsColabours", "project");
		
		$response->setOk();
		
		//nastaveni odpovedi
		$response["project"] = $project;
		$response["colabour"] = $colabours;
		$response["label"] = $labels;
		
		$this->_sendToRender($response, $objectInfo["format"], "get");
	}
	
	protected function _list($objectInfo) {
		//priprava dat
		$tableProjects = new Application_Model_Projects();
		$response = new Library_Response();
		
		//vyhodnoceni zdrojoveho uzivatele
		$userId = isset($_REQUEST["user"]["id"]) ? $_REQUEST["user"]["id"] : $this->_user->id;
		
		//nalezeni projektu uzivatele
		$adapter = $tableProjects->getAdapter();
		
		$projects = $tableProjects->fetchAll($adapter->quoteInto("user_id = ?", $userId), "project_name");
		
		//odeslani odpovedi
		$response["project"] = $projects;
		$response->setOk();
		
		$this->_sendToRender($response, $objectInfo["format"], "list");
	}
	
	protected function _sendArchive($objectInfo) {
		//vypunuti layoutu a view rendereru
		$this->_helper->layout()->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		$response = new Library_Response();
		
		//priprava dat
		try {
			$tableProjects = new Application_Model_Projects();
			$project = $tableProjects->find($objectInfo["id"])->current();
			
			if (!$project) {
				$response->setStatus("PROJECT_NOT_FOUND", 404);
				throw new Zend_Exception("Project id " . $objectInfo["id"] . " not found");
			}
			
			//nacteni adredare
			$directory = $project->findParentRow("Application_Model_DocumentsDirectories", "directory");
			
			if (!$directory) {
				$response->setStatus("ROOT_NOT_FOUND", 500);
				throw new Zend_Exception("Root directory id " . $project->directory_id . " not found");
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, "", "");
			return;
		}
		
		//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
		$hashList = array();
		$this->_writeDocuments($root, $zip, $hashList);
		
		//vytvoreni a zapsani indexu souboru
		$index = array();
		
		foreach ($hashList as $path => $uuid) {
			$index[] = "$path $uuid";
		}
		
		//vygenerovani timestampu
		$timestamp = new Zend_Date();
		
		//vegenerovani formatu
		$format = Zend_Date::YEAR . "-" . Zend_Date::MONTH . "-" . Zend_Date::DAY . " " . Zend_Date::HOUR . ":" . Zend_Date::DAY . ":" . Zend_Date::SECOND;
		
		//zapsani do zipu
		$zip->addFromString(".project-" . $project->directory_id, $timestamp->get($format) . "\n" . implode("\n", $index));
		
		$zip->close();
		
		//odeslani hlavicek
		header("Content-Type: application/zip");
		readfile($zipName);
	}
	
	protected function _writeDocuments(Library_Virtual_Directory $directory, ZipArchive $zip, & $hashList) {
		//vytvoreni adredare
		$zip->addEmptyDir($directory->getPath());
		
		//vytvoreni podadredsaru
		$directories = $directory->getDirs();
		
		foreach ($directories as $dir) {
			$this->_writeDocuments($dir, $zip, $hashList);
		}
		
		//zapsani dokumentu
		$documents = $directory->getDocuments();
		
		foreach ($documents as $document) {
			$document->addToArchive($zip);
			
			//zapsani dokumentu do hashlistu
			$hashList[sha1($document->getPath())] = $document->getUuid();
		}
	}
}