<?php
class Directory_DeleteController extends Library_Controller {
	public function __call($methodName, $args) {
		//nastaveni objektu
		$response = new Library_Response();
		$objectInfo = $this->_parseActionName($methodName);
		
		//vytvoreni instance tabulky adresaru a nacteni adresare
		$tableDirectories = new Application_Model_DocumentsDirectories();
		
		/**
		 * @var Model_Row_Directory $directory
		 */
		$directory = $tableDirectories->find($objectInfo["id"])->current();
		
		//kontrola existence adresare
		if (!$directory) {
		    $response->setStatus("DIRECTORY_NOT_FOUND", 404);
		    $this->_sendToRender($response, $objectInfo["format"]);
		    return;
		}
		
		//nacteni rodicovskeho adresare
		$parentDir = $directory->findParentRow($tableDirectories);
		
		//kontrola existence, pokud adresar neexistuje, zamitne se smazani adresare
		if (!$parentDir) {
		    $response->setStatus("DIRECTORY_IS_ROOT", 403);
		    $this->_sendToRender($response, $objectInfo["format"]);
		    return;
		}
		
		//kontrola opravneni pristupu
		$user = $this->_user;
		
		$groupList = $user->findDependentRowset("Application_Model_UsersHasManyUsersGroups", "user");
		$groups = array();
		
		foreach ($groupList as $group) {
			$groups[] = $group->user_group_id;
		}
		
		$permisions = $parentDir->getPermisions($user->id, $groups);
		
		//pokud nema uzivatel opravneni cist, pripoji se chybove hlaseni
		if (!$permisions->write) {
		    $response->setStatus("NO_WRITE_PERMISIONS", 403);
		    $this->_sendToRender($response, $objectInfo["format"]);
		    return;
		}
		
		//kontrola jestli je adresar prazdny
		$subDirs = $directory->findDependentRowset($tableDirectories);
		
		if ($subDirs->count()) {
		    $response->setStatus("DIRECTORY_NOT_EMPTY", 405);
		    $this->_sendToRender($response, $objectInfo["format"]);
		    return;
		}
		
		$subFiles = $directory->findDependentRowset("Application_Model_DocumentsDirectoriesHasManyDocuments");
		
		if ($subFiles->count()) {
		    $response->setStatus("DIRECTORY_NOT_EMPTY", 405);
		    $this->_sendToRender($response, $objectInfo["format"]);
		    return;
		}
		
		$directory->delete();
		
		$response->setOk();
		$response["parent"] = $parentDir;
		$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("delete-html");
				break;
			
			case "json":
			
			default:
				$this->_helper->viewRenderer("delete-json");
		}
	}
}