<?php
class Group_GetController extends Library_Controller {
	public function __call($methodName, $args) {
		$objectInfo = $this->_parseActionName($methodName);
		
		//kontorla jestli se nejedna o pozadavek na vyspis skupin
		if ($objectInfo["id"] == "list") {
			$this->_list($objectInfo["format"]);
			return;
		}
		
		$response = new Library_Response();
		
		//nacteni informaci o skupine
		$tableGroups = new Application_Model_UsersGroups();
		$group = $tableGroups->find($objectInfo["id"])->current();
		
		if (!$group) {
			//skupina nebyla nalezena
			$response->setStatus("GROUP_NOT_FOUND", 404);
			$this->_sendToRender($response, $objectInfo["format"]);
			return;
		}
		
		//nacteni lidi ve skupine
		$users = $group->findManyToManyRowset($this->_user->getTable(), "Application_Model_UsersHasManyUsersGroups", "group", "user");
		
		$response->setOk();
		$response["group"] = $group;
		$response["users"] = $users->toArray();
		
		$this->_sendToRender($response, $objectInfo["format"]);
	}
	
	/**
	 * metoda pro nacteni seznamu uzivatelu
	 * @param string $format format odpovedi
	 */
	protected function _list($format) {
		//nactei seznamu uzivatleu do pole
		$tableGroups = new Application_Model_UsersGroups();
		
		$groups = $tableGroups->fetchAll(null, "group_name")->toArray();
		
		if ($format != "html") {
			$this->_helper->layout()->disableLayout();
		}
		
		//vytvoreni odpovedi a jeji nastaveni
		$response = new Library_Response();
		
		$response->setOk();
		$response["groups"] = $groups;
		
		$this->view->response = $response;
		
		//vyhodnoceni formatu
		switch ($format) {
			case "html":
				$this->_helper->viewRenderer("list-html");
				
				return;
				
			case "json":
				
			default:
				$this->_helper->viewRenderer("list-json");
		}
	}
	
	protected function _sendToRender(Library_Response $response, $format) {
		//zapsani do view
		$this->view->response = $response;
		$response->sendHeader();
		
		if ($format != "html") {
			$this->_helper->layout()->disableLayout();
		} else {
			//pozadovan je format HTML, vyhodnoti se, zda se ma zobrazit formular pro editaci nebo obycejny
			$editable = false;
			
			if ($this->_user->id == 1) {
				//uzivatel je root
				$editable = true;
			} else {
				//uzivatel neni roots, nactou 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"));
				$editable = (bool) $role->count();
			}
		}
		
		//vyhodnoceni formatu
		switch ($format) {
			case "html":
				if ($editable) {
					$this->_helper->viewRenderer("getedit-html");
				} else {
					$this->_helper->viewRenderer("get-html");
				}
				
				break;
			
			case "json":
			
			default:
				$this->_helper->viewRenderer("get-json");
		}
	}
}