<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2007 - 2013 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flController Class
 *
 * The base class from which all controllers should be derived.
 *
 * @package fusionLib
 */
abstract class flController {

	/**
	 * The request object.
	 *
	 * @var flRequest
	 */
	protected $request;

	/**
	 * The router object.
	 *
	 * @var flRouter
	 */
	protected $router;

	/**
	 * The response object.
	 *
	 * @var flResponse
	 */
	protected $response;

	/**
	 * The instance of the action class if using one.
	 *
	 * @var flControllerAction
	 */
	protected $actionClass = null;

	/**
	 * Construct the object.
	 *
	 * @param flRouter $router The router object.
	 * @param flRequest $request The request object.
	 */
	function __construct($router, $request) {
		$this->router = $router;
		$this->request = $request;
	}

	/**
	 * Return the request object.
	 *
	 * @return flRequest The request object.
	 */
	function getRequest() {
		return $this->request;
	}

	/**
	 * Set the response object.
	 *
	 * @param flResponse $response The response object.
	 * @return flController This object.
	 */
	function setResponse($response) {
		$this->response = $response;
		return $this;
	}

	/**
	 * Return the router object.
	 *
	 * @return flRouter The router object.
	 */
	function getRouter() {
		return $this->router;
	}

	/**
	 * Return the response object.
	 *
	 * @return flResponse The response object.
	 */
	function getResponse() {
		return $this->response;
	}

	/**
	 * Get the instance of the action class if using one.
	 *
	 * @return flControllerAction The instance of the action class or null if not using an action class.
	 */
	function getActionClass() {
		return $this->actionClass;
	}

	/**
	 * Dispatch the given action on the controller, if the action is not available then
	 * an attempt is made to load an action class, if this is also not found a
	 * not found exception is thrown.
	 *
	 * @param string $action The action to invoke.
	 * @throws flExceptionNotFound
	 */
	function dispatch($action) {
		if(method_exists($this, $action .= 'Action'))
			$this->$action();
		else {
			try {
				class_exists($action = substr(get_class($this), 0, -10) . ucfirst($action));
				$this->actionClass = new $action($this);
			} catch(flExceptionLoadClass $e) {
				throw new flExceptionNotFound();
			}
			$this->actionClass->process();
		}
	}
}
