<?php
class Controller {
	var $directory;
	var $default;
	var $error;
	var $pre_action = array();

	function __construct(&$locator) {
		$this->locator =& $locator; 
	}
	
	function setDirectory($directory) {
		$this->directory = $directory;
	}
		
	function setDefault($class, $method) {
		$this->default = $this->forward($class, $method);
	}
	
	function setError($class, $method) {
		$this->error = $this->forward($class, $method);
	}
	
	function addPreAction($class, $method) {
		$this->pre_action[] = $this->forward($class, $method);
	}
	
	function forward($class, $method) {
		$action = array(
			'class'  => $class,
			'method' => $method
		);
		
		return $action;
  	}
	
  	function dispatch(&$request) {
		$action = $this->requestHandler($request);
		
		$i = 0;
		
		while ($action) {
			if ($i > 4) {
				exit('Error: Maximum number of forwards has been exceeded!');
			}
			
			$i++;
			
			foreach ($this->pre_action as $pre_action) {
				$result = $this->execute($pre_action);
						
				if ($result) {
					$action = $result;
						 
					break;
				}
			}
			
			$action = $this->execute($action);
		}
  	}
	
	function execute($action) {
		$file = $this->directory . basename($action['class']) . '.php';
		 
		if (file_exists($file)) {
			require_once($file);
			
			 $controller = 'Controller' . preg_replace('/[^a-zZ-Z0-9]/', NULL, $action['class']);
			
			 $class = new $controller($this->locator);

			if (method_exists($class, $action['method'])) {
//				print_r($action['method']);exit;
				return $class->{$action['method']}($this->locator);
			} else {

				return $this->error;
			}
		} else {

			return $this->error;
		}
	}
	
	function requestHandler(&$request) {
	    if ($request->has('controller')) {
			$class = $request->get('controller');
			
			if ($request->has('action')) {
				$method = $request->get('action');
			} else {
				$method = 'index';
			}

			return $this->forward($class, $method);
	    } else {
			if ($request->has('controller','POST')) {
				$class = $request->get('controller','POST');
				
				if ($request->has('action')) {
					$method = $request->get('action');
				} else {
					$method = 'index';
				}
	
				return $this->forward($class, $method);
			}else
			{		
	        	return $this->default;
			}
	    }
	}				
}
?>