<?php
class Addressary_PostController extends Library_Controller {
	public function __call($methodName, $args) {
		$objectInfo = $this->_parseActionName($methodName);
		
		//konotrla formatu
		if (empty($objectInfo["format"])) {
			//format je prazdny
			$objectInfo["format"] = "json";
		}
		
		//vytvoreni odpovedi
		$response = new Library_Response();
		
		//kontrola dat
		try {
			//pokus o nacteni uzivatele
			$user = $this->_tableUsers->find($objectInfo["id"])->current();
			
			if (!$user) {
				//uzivatel nebyl nalezen
				$response->setStatus("USER_NOT_FOUND", 404);
				throw new Zend_Exception("User id " . $objectInfo["id"] . " not found");
			}
			
			//kontorla jestli je uz uzivatel v tabulce zanesen
			$tableAddressary = new Application_Model_MessagesAddressary();
			$record = $tableAddressary->fetchRow($tableAddressary->select(false)->where("user_id = ?", $this->_user->id)->where("target_user_login like ?", $user->username));
			
			if ($record) {
				//uzivatel je zanesen
				$response->setStatus("USER_IS_IN_ADDRESSARY", 409);
				throw new Zend_Exception("User id " . $user->id . " is in addressary");
			}
		} catch (Zend_Exception $e) {
			//nastavnei rendereru
			$this->_sendToRender($response, $objectInfo["format"]);
			return;
		}
		
		//zaneseni uzivatele do adresare
		$row = $tableAddressary->createRow(array(
			"user_id" => $this->_user->id
			, "target_user_login" => $user->username
		));
		
		$row->save();
		
		//nastaveni a odeslani odpovedi
		$response->setOk();
		$response["contact"] = $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");
		}
	}
}
?>