<?php 


class Route{
	static $listRouts = [];
	static $generateJsCss = true;
	static $appFileName = "app";
	static function is($urls,$callback = null,$type=""){
		if(is_null($callback)) return self::in($urls);
		if(is_string($urls)) $urls = [$urls];
		foreach ($urls as $key => $url) {
			$urls[$key] = self::dispatch($url);
		}
		self::$listRouts[] = [
			"urls" => $urls,
			"callback" => $callback,
			"type" => $type,
		];
	}
	static function isJs($callback,$arg1 = null){
		if (is_string($callback) && is_callable($arg1)) {
			$callback = $arg1;
		}
		return self::is("",$callback,"js");
	}
	static function isCss($callback,$arg1 = null){
		if (is_string($callback) && is_callable($arg1)) {
			$callback = $arg1;
		}
		return self::is("",$callback,"css");
	}
	static function inThis($callback){
		self::is(self::url(),$callback);
	}

	static $listParams = [];
	static function param($name,$callback){
		if(empty(self::$listParams[$name])) self::$listParams[$name] = [];
		self::$listParams[$name][] = $callback;
	}
	static function checkParam($name,&$data){
		if (is_array(self::$listParams[$name])) {
			foreach (self::$listParams[$name] as $fn) {
				$fn($data);
			}
		}
	}
	/*
		return like "/page/test" or "/" ; 
	*/
	static function url(){
		if (isset($_SERVER)) {
			$u = $_SERVER["REQUEST_URI"];
			$u = explode("?",$u)[0];
			$u = explode("#",$u)[0];
			return $u;
		}
		return "/";
	}


	static function dispatch($url){
		foreach (self::$listDispatch as $args) {
			if (preg_match("/".$args["key"]."/i", $url)) {
				if (is_callable($args["value"])) {
					ob_start();
					$fn = $args["value"];
					$fn();
					$url = preg_replace("/".$args["key"]."/i",ob_get_clean(),$url);
				}else{
					$url = preg_replace("/".$args["key"]."/i",$args["value"],$url);
				}
			}
		}
		return $url;
	}
	static $listDispatch = [];
	static function dispatchAdd($key,$value){
		self::$listDispatch[] = ["key"=>$key,"value"=>$value];
	}


	static function in($pattren,&$match = null,$isregex = false){
		$pattren = self::dispatch($pattren);
		if ($isregex) {
			return preg_match($pattren, self::url(),$match);
		}

		$urlBase = self::url();
		preg_match_all("/\{(?<name>[a-zA-Z0-9_-]+)\:(?<type>[a-zA-Z0-9_-]+)\}/i",$pattren,$wtypes);
		preg_match_all("/\{(?<name>[a-zA-Z0-9_-]+)\}/i",$pattren,$arg);
		$map = [];
		foreach ($wtypes[0] as $key => $value) {
			$id = uniqid();
			switch (strtolower(trim($wtypes["type"][$key]))) {
				case 'num':
					$map[$id] = "(?<".$wtypes["name"][$key].">[0-9]+)";
					$pattren = str_replace($value, "¤-$id-¤", $pattren);
				break;
				case 'slugs':
					$map[$id] = "(?<".$wtypes["name"][$key].">[\s\S]*?)";
					$pattren = str_replace($value, "¤-$id-¤", $pattren);
				break;
				default:
					$map[$id] = "(?<".$wtypes["name"][$key].">[^\\/]*?)";
					$pattren = str_replace($value, "¤-$id-¤", $pattren);
				break;
			}
		}
		$map["routeetoilsystem"] = "[\s\S]*?";
		$pattren = preg_replace("/\*/i", "¤-routeetoilsystem-¤", $pattren);
		foreach ($arg[0] as $key => $value) {
			$id = uniqid();
			$map[$id] = "(?<".$arg["name"][$key].">[^\\/]*?)";
			$pattren = str_replace($value, "¤-$id-¤", $pattren);
		}
		$pattren = preg_replace("/([\/\.])/", '\\\$1', $pattren);
		foreach ($map as $key => $value) {
			$pattren = str_replace("¤-$key-¤", $value, $pattren);
		}

		if(empty($pattren)) return true;
		$pattren .= "\/?$";
		if(!preg_match("/^\/?$pattren/i",$urlBase,$args)){
			return false;
		}
		if(!is_array($match))$match = [];
		foreach ($args as $key => $value) {
			if (is_string($key)) {
				$match[$key] = urldecode($value);
			}
		}
		foreach ($match as $key => $value) {
			self::checkParam($key,$match);
		}
		return true;
	}
	static function rmvTag($code,$tags = ["script","style"]){
		if(is_string($tags)) $tags = explode(",",$tags);
		foreach ($tags as $tag) {
		    $code = trim($code);
		    if(preg_match("/^\s*<".$tag."[^>]*>/i", $code)) $code = preg_replace("/^\s*<".$tag."[^>]*>/i", "", $code);
		    if(preg_match("/<\/".$tag.">\s*$/i", $code)) $code = preg_replace("/<\/".$tag.">\s*$/i", "", $code);
		}
	    return $code;
	}
	static function exe(){
		if (self::in("js-plugins/".self::$appFileName.".js")) {
			$c = ob_get_clean();
			header("Content-Type: application/javascript");
			foreach (self::$listRouts as $root) {
				if($root["type"] == "js"){
					$fn = $root["callback"];
					ob_start();
					$fn([]);
					echo ";".self::rmvTag(ob_get_clean()).";";
				}
			}
			exit();
		}elseif(self::in("css-plugins/".self::$appFileName.".css")){
			$c = ob_get_clean();
			header("Content-Type: text/css");
			foreach (self::$listRouts as $root) {
				if($root["type"] == "css"){
					$fn = $root["callback"];
					ob_start();
					$fn([]);
					echo self::rmvTag(ob_get_clean());
				}
			}
			exit();
		}else{
			if (self::$generateJsCss) {
				view::set("js-lib","<script src='/js-plugins/".self::$appFileName.".js?v=".time()."'></script>",true);
				view::set("css-lib",'<link rel="stylesheet" type="text/css"  href="/css-plugins/'.self::$appFileName.'.css?v='.date("d-m-H").'" />',true);
			}else{
				view::set("js-lib","<script src='/js-plugins/".self::$appFileName.".js?v=".time()."'></script>",true);
				view::set("css-lib",'<link rel="stylesheet" type="text/css"  href="/css-plugins/'.self::$appFileName.'.css?v='.date("d-m-H").'" />',true);
			}	
			foreach (self::$listRouts as $root) {
				if(is_array($root["urls"]) && empty($root["type"])){
					$args = [];
					$active = false;
					foreach ($root["urls"] as $url) {
						$rep = [];
						if (self::in($url,$rep)) {
							$active = true;
							if(is_array($rep)){
								$args += $rep;
							}
						}
					}
					if($active){
						$fn = $root["callback"];
						$fn($args);
					}
				}
			}
		}


	}
}


