<?php
class User_GetController extends Library_Controller {	
	public function __call($methodName, $args) {
		//naparsovani objektu
		$objectInfo = $this->_parseActionName($methodName);

		//kontorla formatu
		if ($objectInfo["format"] != "html") {
			//pozadovany format neni html, vypne se layout
			$this->_helper->layout()->disableLayout();
		}
		
		//vyhodnoceni id objektu
		if (strtolower($objectInfo["id"]) == "list") {
			$this->_list($objectInfo["format"]);
			return;
		}
		
		//vytvoreni odpovedi
		$response = new Library_Response();
		
		//nacteni informaci o uzivateli
		/* @var $user Application_Model_Row_User */
		$user = $this->_tableUsers->fetchRow($this->_tableUsers->select(false)
			->where("username like ?", $objectInfo["id"])->orWhere("id = ?", $objectInfo["id"]));
			
		if ($user) {
			//uzivatel bylnalezen, nactou se role a skupiny
			$roles = $user->findManyToManyRowset("Application_Model_UsersRoles", "Application_Model_UsersHasManyUsersRoles", "user", "role");
			$groups = $user->findManyToManyRowset("Application_Model_UsersGroups", "Application_Model_UsersHasManyUsersGroups", "user", "group");
			
			//zapsani do odpovedi
			$response->setOk();
			$response["user"] = $user;
			$response["roles"] = $roles;
			$response["groups"] = $groups;
		} else {
			//uzivatel nebyl nalezen
			$response->setStatus("USER_NOT_FOUND", 404);
		}
		
		//vyhodnoceni formatu a odeslani odpovedi
		$this->view->response = $response;
		
		switch ($objectInfo["format"]) {
			case "html":
				//vyhodnoceni jestli ma uzivatel opravneni menit udaje
				if ($this->_user->id == 1 || ($this->_user->id == $user->id && $user->id != 2)) {
					//uzivatel ma opravneni menit udaje
					$this->_helper->viewRenderer("useredit-html");
					$this->view->thisUser = $this->_user;
				} else {
					//uzivatel nema opravneni menit udaje
					$this->_helper->viewRenderer("user-html");
				}
				
				break;
			
			case "json":
			
			default:
				$this->_helper->viewRenderer("user-json");
		}
		
		$response->sendHeader();
	}
	
	/**
	 * metoda pro nacteni seznamu uzivatelu
	 * @param string $format format odpovedi
	 */
	protected function _list($format) {
		//nactei seznamu uzivatleu do pole
		$users = $this->_tableUsers->fetchAll()->toArray();
		
		//odstraneni citlivych informaci
		foreach ($users as & $user) {
			unset($user["salt"], $user["password"], $user["cookie"]);
		}
		
		//vytvoreni odpovedi a jeji nastaveni
		$response = new Library_Response();
		
		$response->setOk();
		$response["users"] = $users;
		
		$this->view->response = $response;
	}
}