<?php
class Project_ColaboursController extends Library_Controller {
	public function __call($methodName, $args) {
		//priprava dat
		$objectInfo = $this->_parseActionName($methodName);
		
		//kontrola odeslani objektu
		if (!isset($_REQUEST["colabours"])) {
			$this->_list($objectInfo);
			return;
		}
		
		//kontrola dat
		$response = new Library_Response();
		$tableProjects = new Application_Model_Projects();
		
		try {
			//nacteni projektu
			$project = $tableProjects->find($objectInfo["id"])->current();
			
			if (!$project) {
				//projekt nebyl nalezen
				$response->setStatus("PROJECT_NOT_FOUND", 404);
				throw new Zend_Exception("Project id " . $objectInfo["id"] . " not found");
			}
			
			//kontorla opravneni
			if ($this->_user->id != $project->user_id && $this->_user->id != 1 && !in_array("PROJECT_MANAGER", $this->_user->getRoles())) {
				//uzivatel neni opravnen delat zmeny
				$response->setStatus("NO_PERMISIONS", 403);
				throw new Zend_Exception("User id " . $this->_user->id . " is not permited to change colabours for project id " . $project->directory_id);
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"], "put");
			return;
		}
		
		//smazani starych asociaci
		$tableAssocs = new Application_Model_ProjectsColabours();
		
		$tableAssocs->delete("directory_id = " . $project->directory_id);
		
		//nacteni novych uzivatelu
		$data = $_REQUEST["colabours"];
		
		if (!is_array($data)) {
			$data = (array) $data;
		}
		
		//nacteni realnych uzivatelu
		$users = $this->_tableUsers->find($data);
		$row = array(
			"user_id" => 0
			, "directory_id" => $project->directory_id
		);
		
		foreach ($users as $user) {
			$row["user_id"] = $user->id;
			
			$tableAssocs->insert($row);
		}
		
		$response->setOk();
		$this->view->project = $project;
		$this->_sendToRender($response, $objectInfo["format"], "put");
	}
	
	protected function _list($objectInfo) {
		//priprava dat
		$response = new Library_Response();
		$tableProjects = new Application_Model_Projects();
		
		//kontrola dat
		try {
			//nacteni projektu
			$project = $tableProjects->find($objectInfo["id"])->current();
			
			if (!$project) {
				//projekt neexistuje
				$response->setStatus("PROJECT_NOT_FOUND", 404);
				throw new Zend_Exception("Project id " . $objectInfo["id"] . " not found");
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"], "list");
			return;
		}
		
		//nacteni spolupracovniku
		$colabours = $project->findManyToManyRowset("Application_Model_Users", "Application_Model_ProjectsColabours", "project", "user");
		
		$response->setOk();
		$response["colabours"] = $colabours;
		
		$this->view->project = $project;
		
		$this->_sendToRender($response, $objectInfo["format"], "list");
	}
}