<?php

// start sessions
session_start();

// define routes
define('DS', DIRECTORY_SEPARATOR);
define('DIR_ROOT', realpath(dirname(__FILE__)));
define('DIR_EXTENSIONS', DIR_ROOT . DS . 'extensions');
define('DIR_COMPONENTS', DIR_ROOT . DS . 'components');

$localIP = getHostByName(getHostName());

// define urls
define('URL_BASE', 'http://'. $localIP .'/PHP');

// define exec mode
define('_EXEC', true);

// load smart object
require(DIR_ROOT . DS . 'smartobject.php');

// load consiguration class
require(DIR_ROOT . DS . 'appconfig.php');

// load templater
require(DIR_ROOT . DS . 'template.php');

// load database class
require(DIR_EXTENSIONS . DS . 'sdatabase.php');

// create primary database instance
global $_database;
$_database = new SDatabase(
	Configuration::MYSQL_PRIMARY_DB_USER,
	Configuration::MYSQL_PRIMARY_DB_PASS,
	Configuration::MYSQL_PRIMARY_DB_NAME,
	Configuration::MYSQL_PRIMARY_DB_HOST,
	Configuration::MYSQL_PRIMARY_DB_PORT,
	Configuration::MYSQL_PRIMARY_DB_CHAR,
	Configuration::MYSQL_PRIMARY_DB_PREFIX
);


/**
* 
*/
class Application
{
	private $id;

	private $active_route;

	private static $instance;


	private function __construct()
	{
		$this->genUID();
		$this->startTemplate();
	}

	
	public static function getInstance()
	{
		if (self::$instance === NULL)
		{
			self::$instance = new self;
		}
		return self::$instance;
	}


	private function genUID()
	{
		$this->id = uniqid();
	}


	private function startTemplate()
	{
		template::start();
	}


	public static function start($option = null)
	{
		$class = self::getInstance();
		$class->route($option);
	}


	public static function getActiveRoute()
	{
		$class = self::getInstance();
		return $class->active_route;
	}


	public static function route($option = null)
	{
		$default = 'index';
		if (is_null($option))
		{
			$option = isset($_GET['option']) ? $_GET['option'] : $default;

			preg_match('/^[a-zA-Z\d]+$/', $option, $matches);
			if (is_array($matches) && isset($matches[0]))
			{
				$option = $matches[0];
			}
			else
			{
				$option = $default;
			}
		}

		$path = DIR_COMPONENTS . DS . $option . '.php';
		if (!file_exists($path))
		{
			$option = $default;
			$path 	= DIR_COMPONENTS . DS . $option . '.php';
		}
		$class = self::getInstance();
		$class->active_route = $option;

		require($path);
		return;
	}
}