<?php
class Group_PostController extends Library_Controller {
	public function __call($methodName, $args) {
		//priprava akce
		$objectInfo = $this->_parseActionName($methodName);
		$response = new Library_Response();
		
		//pokus o nacteni skupiny
		$tableGroups = new Application_Model_UsersGroups();
		$group = $tableGroups->fetchRow($tableGroups->select(false)->where("group_name like ?", $objectInfo["id"]));
		
		if ($group) {
			//skupina nebyla nalezena
			$response->setStatus("GROUP_EXISTS", 404);
			$this->_sendToRender($response, $objectInfo["format"]);
			return;
		}
		
		//kontrola opravneni
		if ($this->_user->id != 1) {
			//uzivatel neni root, zkontorluji se role
			$tableRoles = new Application_Model_UsersRoles();
			
			$role = $this->_user->findManyToManyRowset($tableRoles, "Application_Model_UsersHasManyUsersRoles", "user", "role", $tableRoles->select(false)->where("role_name like ?", "GROUP_MANAGER"));

			if (!$role->count()) {
				//role nebyla nalezena, uzivatel nema opravneni
				$response->setStatus("NO_PERMISIONS_TO_CREATE_GROUP", 403);
				$this->_sendToRender($response, $objectInfo["format"]);
				return;
			}
		}
		
		//kontorla jeslti je jmeno skupiny validni
		$empty = new Zend_Validate_NotEmpty();
		$alnum = new Zend_Validate_Alnum();
		
		if (!($empty->isValid($objectInfo["id"]) && $alnum->isValid($objectInfo["id"]))) {
			//role nebyla nalezena, uzivatel nema opravneni
			$response->setStatus("GROUP_NAME_INVALID", 400);
			$this->_sendToRender($response, $objectInfo["format"]);
			return;
		}
		
		//kontorla jmena proti vyhrazenym jmenum
		if ($objectInfo["id"] == "list") {
			//role nebyla nalezena, uzivatel nema opravneni
			$response->setStatus("LIST_IS_RESERVED_NAME", 400);
			$this->_sendToRender($response, $objectInfo["format"]);
			return;
		}
		
		//vytvoreni skupiny
		$group = $tableGroups->createRow(array("group_name" => $objectInfo["id"]));
		$group->save();
		
		$response["group"] = $group;
		
		//nastavnei odpovedi
		$response->setOk();
		$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");
		}
	}
}