<?php

class View{
	private $_view,$_variables,$_cssFiles,$_jsFiles;
	
	public function __construct($view, $variables=array()) {
		$this->_view=$view;
		if (isset($variables['this']))
			throw new Exception("'this' is a reserved variable index");
		$this->_variables=$variables;
		$this->_cssFiles=array();
		$this->_jsFiles=array();
	}
	
	// This is here to force the IConvertible interface use
	private static function DoConversion(IConvertible $converter, $item){
		return $converter->Convert($item);
	}
	
	public function GetHTMLFromTemplate($template) {
		$viewContent=file_get_contents('View/'.$this->_view);
		$htmlParts=array();
		
		// Make the sent variables available to the view
		foreach ($this->_variables as $var=>$value)
			eval('$'.$var.'=$this->_variables[\''.$var.'\'];'.PHP_EOL);
		
		// Break the view up to be applied to the template
		$matches=array();
		preg_match_all('/@(.*)\{(.*)\}@/sU', $viewContent,$matches);
		for ($i=0;$i<count($matches[0]);$i++)
			$htmlParts[$matches[1][$i]]=$matches[2][$i];
		
		// Populate the template
		$templateHTML=file_get_contents($template);
		$code=preg_replace_callback("/\{@(.*)\}/", function($match) use ($htmlParts){
			if (isset($htmlParts[$match[1]]))
				return $htmlParts[$match[1]];
			return "";
		}, $templateHTML);
		
		// Process the new PHP
		//file_put_contents("output.php", $code);
		ob_start();
		eval('?>'.$code.'<?php ');
		$output=ob_get_clean();
		
		// Do the convertible tags
		$output=preg_replace_callback('/<convertible type="(.*)">(.*)<\/convertible>/sU', function($match) {
			if (class_exists($match[1],false))
				return self::DoConversion(new $match[1](), $match[2]);
			return $match[2];
		}, $output);
		
		return $output;
	}
	
	public function RegisterCSSFile($path){
		$this->_cssFiles[]=$path;
	}
	
	public function GetCSSFiles() {
		return $this->_cssFiles;
	}
	
	public function RegisterJSFile($path){
		$this->_jsFiles[]=$path;
	}
	
	public function GetJSFiles() {
		return $this->_jsFiles;
	}
}