<?php
final class App {
	private static $getInitial = array();
	/**
	 * run
	 *
	 * @access public
	 * @return void
	 */
	public function run() {
		$param = self :: parsePath();
		$controller = $param['controller'] . 'Action';
		$action = $param['action'];
		if ($action == 'list') $action = 'showList';
		isset(self :: $getInitial[$controller]) or self :: $getInitial[$controller] = new $controller($action);
		if (method_exists(self :: $getInitial[$controller], $action)) self :: $getInitial[$controller] -> $action();
		else show_error($action . ' ' . L('ERROR_ACTION'));
	}

	/**
	 * Parse URL Path
	 *
	 * @access private
	 * @return void
	 */
	private function parsePath() {
		$c = trim(R('c'));
		$c or $c = DEFAULT_C;
		$a = trim(R('a'));
		if (!$a && defined('DEFAULT_A')) $a = DEFAULT_A;
		if ($a) {
			$a = strtolower($a);
			if (strstr($a, '_')) {
				$t = explode('_', $a);
				foreach($t as $k => $v) $a = $k?$a . ucwords($v):$v;
			}
		} else $a = 'defaults';
		return array('controller' => parse_name(strtolower($c), 1), 'action' => $a);
	}
	/**
	 * 模板调用函数
	 * $name,模板名称
	 *
	 * @return string
	 */
	public function tpl($name) {
		$styleDir = defined('STYLE')?STYLE:C('style');
		if (MODULE_DIR && is_dir(JXCMS_ROOT . MODULE_DIR . 'templates/')) {
			$tmpDir = 'Templates_Module/' . MODULE_DIR;
			$rootDir = JXCMS_ROOT . MODULE_DIR;
		} else {
			$tmpDir = 'Templates';
			$rootDir = JXCMS_ROOT;
		}
		$objFile = JXCMS_ROOT . 'jxcms/Runtime/' . $tmpDir . '/' . ucwords($styleDir) . '/' . $name . '.php';
		$parse = 0;
		// 检测是否需要模板编译 start
		if (!file_exists($objFile) || C('APP_RUN_TYPE', 1)) {
			$tplFile = self :: tplPath($name, $styleDir, $rootDir);
			if (!file_exists($objFile) || filemtime($tplFile) > filemtime($objFile)) $parse = 1;
		}
		// end
		if ($parse) {
			$dir = C('APP_DIR', 1);
			if ($rootDir == JXCMS_ROOT && MODULE_DIR) $dir = str_replace(MODULE_DIR, '', $dir);
			View :: getInitial($styleDir, $rootDir, $dir) -> template($tplFile, $objFile);
		}
		return $objFile;
	}
	/**
	 * 获取模板路径
	 *
	 * @return string
	 */
	private function tplPath($name, $styleDir, $rootDir) {
		$ext = defined('TPLEXT')?TPLEXT:C('tplext');
		$tplFile = $rootDir . 'templates/' . $styleDir . '/' . $name . $ext;
		if (!is_file($tplFile)) {
			if ($styleDir != 'admin')
				$tplFile = $rootDir . 'templates/default/' . $name . $ext;
			if (!is_file($tplFile))
				show_error('Tpl file ' . $name . $ext . ' is not exist!');
		}
		return $tplFile;
	}
}