<?php

function file_exists_multi($filename, $dirs) {
	foreach($dirs as $dir) {
		if (file_exists($dir.$filename))
			return true;
	}
	return false;
}


function show_test($message, $result) {
//	if (!$result)
		echo $message."…\t".($result ? "OK" : "ERROR")."\n";
}

function check_path($path) {
	show_test("check path “".$path."”", file_exists($path));
}

function check_path_multi($path, $dirs) {
	show_test("check path “".$path."” in ".implode(", ", $dirs), file_exists_multi($path, $dirs));
}

function check_img($node) {
	$src = $node->getAttribute("src");
	check_path($src);
}

function check_project($id) {
	check_path("../../proj/".$id.".prj");
	check_path("../../schema/".$id.".dia");
	check_path("../../struc/".$id.".str");
}

function check_javascript_call($fct, $args) {
	if ($fct == "app.thermoptim.loadProject") {
		check_project($args[0]);
	}
	else if ($fct == "app.thermoptim.loadCycle") {
		check_path_multi($args[0], array("../../cycle/gaz/", "../../cycle/vap/"));
	}

}

function check_javascript_cmd($cmd) {
	if (preg_match('/(.*)\((.*)\);/', $cmd, $arr)) {
		$fct = $arr[1];
		$json = "[".str_replace("'", "\"", $arr[2])."]";
		$args = json_decode($json);
		check_javascript_call($fct, $args);
	}
}

function check_javascript($str) {
	$cmds = explode(";", $str);
	foreach($cmds as $cmd) {
		$cmd = trim($cmd);
		if ($cmd) {
			check_javascript_cmd($cmd.";");
		}
	}
}

function check_element($node) {
	if ($node->tagName == "img") {
		check_img($node);
	}
	if ($node->hasAttribute("onclick")) {
		check_javascript($node->getAttribute("onclick"));
	}
	if ($node->hasAttribute("onready")) {
		check_javascript($node->getAttribute("onready"));
	}
}

function check_childs($parent) {
	for ($node = $parent->firstChild; $node; $node = $node->nextSibling) {
		if ($node->nodeType == XML_ELEMENT_NODE) {
			check_element($node);
			check_childs($node);
		}
	}
}

function check_file($path) {
	echo "Checking file ".$path."…\n";

	$doc = new DOMDocument();
	$doc->loadHTMLFile($path, LIBXML_NOERROR);
	check_childs($doc);
}

function check_files($list) {
	foreach($list as $filename) {
		check_file($filename);
	}
}


unset($argv[0]);
check_files($argv);
