<?php

namespace Tools;

abstract class AHttpController extends AController
{
	/**
	 * @var string $theme 
	 * Theme's directory
	 * Accessible read-only
	**/
	private $theme;

	/**
	 * @var \Tools\Output $output
	 * Output manager
	**/
	private $output;

	public function __construct($context, $params)
	{
		parent::__construct($context, $params);
		$this->output = new \Tools\Output($context);
		$this->loadTheme();
	}

	/**
	 * Init theme
	**/
	private function loadTheme()
	{
		$themeName = \Entity\Config::getConfig(null, "theme", "default");
		$themeDir = $this->context->router->themesPath.$themeName.'/';
		if (!is_dir($themeDir))
			throw new \Exception\Error404();
		$this->theme = $themeDir;
	}

	/**
	 * Run the controller. Entry point
	**/
	public function start()
	{
		//TODO trigger hook GET, POST
		//TODO call some hooks
		$this->run();
		//TODO calls some hooks
	}

	/**
	 * Load and render a file
	 * @param string $viewFile template view to load (from theme)
	 * @return boolean true on success
	**/
	protected function render($viewFile)
	{
		$themedir = opendir($this->theme);
		$exists = false;
		while ($dir = readdir($themedir))
		{
			if ($dir !== $viewFile || is_dir($this->theme.'/'.$dir))
				continue;
			$exists = $dir;
		}
		closedir($themedir);
		if ($exists === false)
			return false;
		$this->output->renderFile($this->theme . $exists);
		return true;
	}

	public abstract function run();

	public function __get($key)
	{
		if ($key === "theme")
			return $this->theme;
		throw new \Exception("Cannot access attribute {$key}");
	}
}

