<?php
class Addressary_DeleteController extends Library_Controller {
	public function __call($methodName, $args) {
		//nacteni objektu
		$objectInfo = $this->_parseActionName($methodName);
		
		//vytvoreni odpovedi
		$response = new Library_Response();
		
		//vytvoreni tabulky
		$tableAddressary = new Application_Model_MessagesAddressary();
		
		//kontorla dat
		try {
			//nacteni zaznamu
			$row = $tableAddressary->find($objectInfo["id"])->current();
			
			if (!$row) {
				//objekt nebyl nalezen
				$response->setStatus("CONTACT_NOT_FOUND", 404);
				throw new Zend_Exception("Contact id " . $objectInfo["id"] . " not found");
			}
			
			//kontorla vlastnika
			if ($this->_user->id != $row->user_id && $this->_user->id != 1) {
				$response->setStatus("CONTACT_IS_NOT_YOURS", 403);
				throw new Zend_Exception("Contact id " . $row->id . " is not own");
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"]);
			return;
		}
		
		//smazani radku
		$row->delete();
		
		$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("delete-html");
				break;
			
			case "json":
			
			default:
				$this->_helper->viewRenderer("delete-json");
		}
	}
}