<?php
/**
 * class application
 *
 * Description for class application
 *
 * @author:
*/
namespace core;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use core\exception\databaseException;

class application {
	private $route = null;

	public function __construct() {
		$this->init();
		$this->execute();
	}

	public function init() {
		$this->runLogging();
		$this->loadConfig();
		$this->runTemplate();
		$this->runDatabase();
		$this->runRouting();
		$this->runAuthorization();
		$this->runFlashMessages();
	}

	private function execute() {
		list($controller_name, $action_name) = $this->route[0];
		$controller_name .= "_controller";
		$action_name .= "_action";

		$class_name = "\\controller\\{$controller_name}";
		
		$area = url::getArea();
		if($area !== false) {
			global $__vendor;
			
			//$__vendor->add("area\\{$this->route[0][2]}\\controller\\", __DIR__."/../area/{$this->route[0][2]}/controller/");

			$class_name = "\\area\\{$this->route[0][2]}\\controller\\{$controller_name}";
		}
		
		if(!class_exists($class_name)) {
			__debug("Controller [$controller_name] no exist!");
		}

		$controller = new $class_name();
		if(!method_exists($controller, $action_name)) {
			__debug("Action [$action_name] in {$controller_name} no exist!");
		}
		
		$controller->controller = $this->route[0][0];
		$controller->action = $this->route[0][1];
		$controller->defaults($this->route[1]);
		$controller->{$action_name}($this->route[1]);
	}

	private function runLogging() {
		global $__logger;

		//$errorHandler = new StreamHandler("_app/log/error.log", Logger::ERROR);

		//$__logger = new Logger("general");
		//$__logger->pushHandler($errorHandler);

		//monologErrorHandler::register($__logger);
	}

	private function loadConfig() {
		global $__config;
		$__config = array();

		$config = new config();

		$settings = $config->settings();
		$__config = array_merge($__config, $settings);

		$database = $config->database((bool)$__config["version"]["production"]);
		$__config = array_merge($__config, $database);

		return true;
	}

	private function runTemplate() {
		global $__template;

		$__template = new template();
	}

	private function runDatabase() {
		global $__config, $__database;
		
		$config = $__config["database"];

		try {
			$__database = new database("mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}", $config["user"], $config["password"]);
			$__database->exec("SET CHARSET {$config['charset']}");

			return true;
		} catch(\PDOException $error) {
			throw new databaseException($error->getMessage(), $error->getCode());
		}

		return false;
	}

	private function runRouting() {
		global $__routing;

		$routing = new routing();
		if(!$routing->is_match()) {
			__debug("No routing!");
			exit;
		}

		$this->route = $routing->get();
		$__routing = $this->route;
	}

	private function runAuthorization() {
		user::init();
	}

	private function runFlashMessages() {
		flashMessages::init();
	}
}
?>