<?php
class Document_PostController extends Library_Controller {
	public function __call($methodName, $args) {
		//inicializace objektu
		$response = new Library_Response();
		$objectInfo = $this->_parseActionName($methodName);

		//hack formatu
		$objectInfo["format"] = $objectInfo["id"];

		//kontrola jestli je soubor odeslan v promenne nebo jako multipart
		if (isset($_FILES["document"])) {
			if (!is_uploaded_file($_FILES["document"]["tmp_name"]["content"])) {
				$response->setStatus("DATA_NOT_FOUND", 400);
				$this->_sendToRender($response, $objectInfo["format"]);
				return;
			}

			//nacteni obsahu souboru
			$_REQUEST["document"]["content"] = file_get_contents($_FILES["document"]["tmp_name"]["content"]);

			//kontrola jestli se ma vzit jmeno dokumentu z jmena souboru
			if (!isset($_REQUEST["document"]["document_name"])) {
				$_REQUEST["document"]["document_name"] = $_FILES["document"]["name"]["content"];
			}

			//kontrola jeslti byl rucne nastaven MIME typ
			if (!isset($_REQUEST["document"]["mime_type"])) {
				$_REQUEST["document"]["mime_type"] = $_FILES["document"]["type"]["content"];
			}
		}

		//kontrola jeslti jsou vsechny informce na svem miste
		if (!isset($_REQUEST["document"]["content"], $_REQUEST["document"]["document_name"])) {
			$response->setStatus("DATA_NOT_FOUND", 400);
			$this->_sendToRender($response, $objectInfo["format"]);
			return;
		}

		$document = $_REQUEST["document"];

		//zapsani velikosti
		$document["size"] = strlen($document["content"]);

		//pokud neni nastaven mime typ, nastavi se jako obecny
		if (!isset($document["mime_type"])) {
			$document["mime_type"] = "application/octet-stream";
		}

		//nastaveni uzivatele
		$document["user_id"] = $this->_user->id;

		//vytvoreni instance tabulky dokumentu
		$tableDocuments = new Application_Model_Documents();

		//ulozeni do databaze
		$row = $tableDocuments->createRow($document);
		$row->save();
		
		//nacteni uuid prvniho dokumentu
		$tableDocumentsHistory = new Application_Model_DocumentsHistory();
		$history = $tableDocumentsHistory->fetchRow($tableDocumentsHistory->getAdapter()->quoteInto("document_last_uuid like ?", $row->uuid));

		//ulozeni obsahu do souboru
		file_put_contents(CONTENT_PATH . "/" . $history->document_first_uuid, $document["content"]);
		
		//vytvoreni symlinku
		symlink(CONTENT_PATH . "/" . $history->document_first_uuid, CONTENT_PATH . "/" . $row->uuid);

		//pokud byl odeslan pozadavek na zarazeni do adresare, soubor se zaradi
		$writedTo = 0;
		
		if (isset($_REQUEST["document"]["directory"])) {
			$tableAssocs = new Application_Model_DocumentsDirectoriesHasManyDocuments();
			
			$data = array(
				"document_uuid" => $row->uuid,
				"document_directory_id" => 0,
				"document_name" => ""
			);
			
			$nullName = new Zend_Db_Expr("NULL");
			
			//nactnei role
			$tableRoles = new Application_Model_UsersRoles();
			$role = $this->_user->findManyToManyRowset($tableRoles, "Application_Model_UsersHasManyUsersRoles", "user", "role", $tableRoles->select(false)->where("role_name like ?", "DOCUMENT_MANAGER"));
			
			$rootPermisions = $this->_user->id == 1 || $role->count();
			
			//kontorla jeslti je treba nacitat skupiny
			if (!$rootPermisions) {
				//uzivatel nema rootovska opravneni, je treba nacist skupiny
				$groupList = $this->_user->findDependentRowset("Application_Model_UsersHasManyUsersGroups", "user");
				$groups = array();
				
				foreach ($groupList as $group) {
					$groups[] = $group->user_group_id;
				}
				
				$tableDirectories = new Application_Model_DocumentsDirectories();
			}
			
			//prochazeni adresaru
			foreach ($_REQUEST["document"]["directory"] as $directoryId => $info) {
				//kontorla dat
				if (!isset($info["write"])) {
					//informace o zapisovatelnosti neni nastavena
					continue;
				}
				
				if (!$info["write"]) {
					//do adresare se name zapisovat
					continue;
				}
				
				//konotrla jmena
				if (!isset($info["document_name"])) {
					$info["document_name"] = $nullName;
				}
				
				//kontorla root permisions
				if ($rootPermisions) {
					//uzivatel ma rootovska opravneni a nemusi se kontrolovat opravneni k adresari
					$data["document_directory_id"] = $directoryId;
					$data["document_name"] = $info["document_name"];
					
					$tableAssocs->insert($data);
					$writedTo++;
				} else {
					//je potreba zkontrolovat opravneni k adredari
					$directory = $tableDirectories->find($directoryId)->current();
					
					if (!$directory) {
						//adredar nebyl nalezen, preskoci se na dalsi
						continue;
					}
					
					//kontorla opravneni
					if (!$directory->getPermisions($this->_user->id, $groups)->write) {
						//uzivatel neni opravnen zapisovat do adresare
						continue;
					}
					
					//zapis asociace
					$data["document_directory_id"] = $directoryId;
					$tableAssocs->insert($data);
					
					$writedTo++;
				}
			}
		}
		
		//pokud nebyl dokument zapsan do zadneho oadresare, zapise se do kose
		if (!$writedTo) {
			$tableTrash = new Application_Model_DocumentsUnassigned();
			$tableTrash->insert(array(
				"uuid" => $document->uuid,
				"user_id" => $this->_user->id,
				"document_name" => $document->document_name
			));
		}

		//nastaveni odpovedi
		$response->setOk();
		$response["document"] = $row;
		
		$this->_sendToRender($response, $objectInfo["format"]);
	}

	protected function _sendToRender(Library_Response $response, $format) {
		//zapsani do view
		$this->view->response = $response;
		$response->sendHeader();

		if ($format != "html") {
			$this->_helper->layout()->disableLayout();
		}

		//vyhodnoceni formatu
		switch ($format) {
			case "html":
				$this->_helper->viewRenderer("post-html");
				break;
					
			case "json":
					
			default:
				$this->_helper->viewRenderer("post-json");
		}
	}
}