<?php
if(!defined('APP_PATH')||!defined('I_PATH')){exit('Access Denied');}
class viewBase {
	public $engine = null;
	public $displayed = FALSE;
	public function __construct()
	{
		if(FALSE == func_get_iglobal(array('view','enabled')))return FALSE;
		if(FALSE != func_get_iglobal(array('view','auto_ob_start')))ob_start();
		$this->engine = syClass(func_get_iglobal(array('view','engine_name')),null,func_get_iglobal(array('view','engine_path')));
		if( func_get_iglobal(array('view','config')) && is_array(func_get_iglobal(array('view','config'))) ){
			$engine_vars = get_class_vars(get_class($this->engine));
			$viewbaseconfigArr = func_get_iglobal(array('view','config'));
			foreach( $viewbaseconfigArr  as $key => $value ){
				if( array_key_exists($key,$engine_vars) )$this->engine->{$key} = $value;
			}
		}
		if( !empty($GLOBALS['LD_I']['sp_app_id']) && isset($this->engine->compile_id) )$this->engine->compile_id = $GLOBALS['LD_I']['sp_app_id'];
		if( empty($this->engine->no_compile_dir) && (!is_dir($this->engine->compile_dir) || !is_writable($this->engine->compile_dir)))__mkdirs($this->engine->compile_dir);
		spAddViewFunction('spUrl', array( 'viewBase', '__template_spUrl'));
	}

	public function display($tplname)
	{
		try {
				$this->addfuncs();
				$this->displayed = TRUE;
				if(func_get_iglobal(array('view','debugging')) && SP_DEBUG)$this->engine->debugging = TRUE;
				$this->engine->display($tplname);
		} catch (Exception $e) {
			syError( func_get_iglobal(array('view','engine_name')). ' Error: '.$e->getMessage() );
		}
	}

	public function addfuncs()
	{
		if( is_array(func_get_iglobal(array('view_registered_functions'))) ){
			$newbaseregistered_functions = func_get_iglobal(array('view_registered_functions'));
			foreach( newbaseregistered_functions as $alias => $func ){
				if( is_array($func) && !is_object($func[0]) )$func = array(syClass($func[0]),$func[1]);
				$this->engine->registerPlugin("function", $alias, $func);
				unset($GLOBALS['LD_I']["view_registered_functions"][$alias]);
			}
		}
	}

	public function __template_spUrl($params)
	{
		$geturl = basename(__FILE__);
		$controller = func_get_iglobal(array('default_controller'));
		$action = func_get_iglobal(array('default_action'));
		$args = array();
		$anchor = null;
		foreach($params as $key => $param){
			if( $key == func_get_iglobal(array('url_controller'))){
				$controller = $param;
			}elseif( $key == func_get_iglobal(array('url_action'))){
				$action = $param;
			}elseif( $key == 'anchor' ){
				$anchor = $param;
			}else{
				$args[$key] = $param;
			}
		}
		return spUrl($geturl, $controller, $action, $args, $anchor);
	}
}