<?php

spl_autoload_register(function($class){
	if (file_exists("Interfaces/$class.php")){
		include("Interfaces/$class.php");
		return;
	}
	if (file_exists("Model/$class.php"))
		include("Model/$class.php");
});

/*include_once 'ApplicationSettings.php';
include_once 'View.php';
include_once 'Helper.php';
include_once 'IConvertible.php';*/

$files=glob("base/*.php");
foreach ($files as $file)
		require_once $file;

class Application{
	protected $_view, $_controller, $_url;
	
	protected function LoadPage($page,$action,$params){
		$controller=self::FindControllerPath($page);
		if ($controller===false){
			$page="E404";
			$controller="Controller/E404.php";
			$params=array($this->_url);
		}
		
		include_once $controller;
		$this->_controller=new $page();
		if (!method_exists($this->_controller, $action))
			$action="Index";
		$this->_view=$this->_controller->$action($params);
	}
	
	function __construct($url) {
		$this->_url;
//		session_start();
		
		$page=ApplicationSettings::GetSetting("general", "default_page");
		$action="Index";
		$params=array();
		
		$parts=explode("/", $url, 3);
		switch (count($parts)){
			case 3:
				if ($parts[2]!='')
					$params=explode("/",$parts[2]);
			case 2:
				//$action=ucfirst($parts[1]);
				$action=$parts[1];
			case 1:
				if ($parts[0]!="")
					$page=$parts[0];
				break;
		}
		
		foreach ($_GET as $key=>$_)
			$params[$key]=filter_input(INPUT_GET, $key);
		foreach ($_POST as $key=>$_)
			if (!is_array($_))
				$params[$key]=filter_input(INPUT_POST, $key);
			else
				$params[$key]=filter_input(INPUT_POST,$key, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
		//$params['cookies']=array();;
		//foreach ($_COOKIE as $key=>$_)
		//	$params['cookies'][$key]=filter_input(INPUT_COOKIE, $key);
		
		$this->LoadPage($page, $action, $params);
	}
	
	public function GetOutput(){
		if (gettype($this->_view)=="object")
			return $this->_view->GetHTMLFromTemplate(ApplicationSettings::GetSetting("general", "template"));
		switch (gettype($this->_view)){
			case "string":
			case "integer":
				return $this->_view;
		}
		return "";
	}
	
	public static function FindControllerPath($controller){
		$controllerLower=strtolower($controller);
		$files=glob("Controller/*.php");
		foreach ($files as $file)
			if (strtolower(basename($file,".php"))==$controllerLower)
				return $file;
		return false;
	}
}