<?php

class FrontController {

	const DEFAULT_CONTROLLER = 'Main';
	const DEFAULT_ACTION = "index";

	private $default_controller;
	private $default_action;
	private $sessionWrapper;

	private $session;
	private $post;
	private $server;

	/**
	 * @var ApplicationControllerFactory
	 */
	private $applicationControllerFactory;

	public function __construct(array & $session,array $post, array $server){
		$this->session = & $session;
		$this->post = $post;
		$this->server = $server;

		$this->setDefaultController(self::DEFAULT_CONTROLLER,self::DEFAULT_ACTION);
		$this->sessionWrapper = new SessionWrapper($session);
		$this->setApplicationControllerFactory(new ApplicationControllerFactory($this->sessionWrapper));
	}

	public function setDefaultController($default_controller,$default_action){
		$this->default_controller = $default_controller;
		$this->default_action = $default_action;
	}

	public function setApplicationControllerFactory(ApplicationControllerFactory $applicationControllerFactory){
		$this->applicationControllerFactory = $applicationControllerFactory;
	}

	public function go(){
		if (isset($this->post['page'])){
			$query_string="page=".$this->post['page'];
		} else {
			$query_string= $this->server['QUERY_STRING'];
		}

		$queryString = new QueryString($this->default_controller,$this->default_action);
		$queryString->createFromString($query_string);

		$controllerName = "{$queryString->controllerName}Controller";
		$actionName = "{$queryString->actionName}Action";

		if (! class_exists($controllerName)){
			$controllerName = "{$this->default_controller}Controller";
		}

		$controller = $this->applicationControllerFactory->getInstance($controllerName);

		if (! method_exists($controller,$actionName)){
			$actionName = "{$this->default_action}Action";
		}
		try {
			$controller->$actionName($queryString->arguments);
		} catch (RedirectException $e){
			$this->sessionWrapper->storeLastMessage($e->getMessageType(),$e->getMessage());
			throw $e;
		}
	}

}