<?php

namespace Vn\Web;

require_once ('vn/lib/app.php');

/**
 * Main class for web applications.
 *
 * Format for $_REQUEST['srv'] variable:
 *  - [serviceName]:[requestDir]/[requestFile]
 **/
class App extends \Vn\Lib\App
{
	private $allowedServices =
	[
		'html',
		'rest',
		'json'
	];

	function run ()
	{
		$this->init ();
		
		$srv = empty ($_REQUEST['srv']) ? '' : $_REQUEST['srv'];
		$explode = explode (':', $srv, 2);

		if (count ($explode) > 0)
			$_REQUEST['service'] = $explode[0];			
		if (count ($explode) > 1)
			$_REQUEST['method'] = $explode[1];

		$service = empty ($_REQUEST['service']) ? 'html' : $_REQUEST['service'];

		if (in_array ($service, $this->allowedServices, TRUE))
		{
			$includeFile = __DIR__."/$service-service.php";
			require_once ($includeFile);

			$className = __NAMESPACE__ .'\\'. hyphenToCamelCase ($service, TRUE) .'Service';
			$service = new $className ($this);
			$service->run ();
		}
		else
			http_response_code (400);
	}

	/**
	 * Gets the configuration file name associated to the current vhost
	 * or the default config file if isn't defined a file for the vhost.
	 **/
	function getConfigFile ()
	{
		if (!empty ($_SERVER['SERVER_NAME'])
		&& preg_match ('/^[\w\-\.]+$/', $_SERVER['SERVER_NAME']))
		{
			$hostSplit = explode ('.', $_SERVER['SERVER_NAME']);
			$configDir = _CONFIG_DIR .'/'. $this->name;
			$hostFile = $configDir .'/config.'. $hostSplit[0] .'.php';
		}

		if (isset ($hostFile) && file_exists ($hostFile))
			return $hostFile;
		else
			return parent::getConfigFile ();
	}
}

?>