<?php
class Sended_DeleteController extends Library_Controller {
	public function __call($methodName, $args) {
		//priprava odpovedi a dat
		$response = new Library_Response();
		$objectInfo = $this->_parseActionName($methodName);
		$tableSended = new Application_Model_MessagesSended();
		
		//nacitani a kontrola dat
		try {
			//nacteni radku
			$row = $tableSended->find($objectInfo["id"])->current();
			
			if (!$row) {
				//radek neexistuje
				$response->setStatus("SENDED_MESSAGE_NOT_FOUND", 404);
				throw new Zend_Exception("Sent message id " . $objectInfo["id"] . " not found");
			}
			
			//kontrola vlastnika
			if ($row->user_id != $this->_user->id) {
				//uzivatel neni valstni zpravy
				$response->setStatus("USER_IS_NOT_OWNER", 403);
				throw new Zend_Exception("User id " . $this->_user->id . " is not owner of sended message id " . $row->id);
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"]);
			return;
		}
		
		//smazani zpravy
		$row->delete();
		
		//nastaveni 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("delete-html");
				break;
			
			case "json":
			
			default:
				$this->_helper->viewRenderer("delete-json");
		}
	}
}