<?php
require_once '..\config.php';
require_once '..\bsw\utils.php';
$returnRawResults = true;

$ivPref = 'http://www.intuview.com/ontology';
//error_reporting(-1);
if (PHP_SAPI !== 'cli')
	die("Usage: namesTester.php listName");
if (count($argv) > 1)
	$listName = $argv[1];
else
	$listName = "regression test.tsv";

if (($handle = fopen($listName, "r")) === FALSE)
	die("failed to open $listName");

$header = fgetcsv($handle, 0, "\t");
dbgPrint("header", $header);

function dbgPrint($name, $obj)
{
	return;
	echo "\r\n$name:\r\n";
	print_r($obj);
	echo "\r\nend $name\r\n";
}

function rowErrPrint($rowObj, $error)
{
	echo $error . ": " . join($rowObj) . "\r\n";
}

$currName = null;

$rowNum = 1;
$numNames = 0;
$numSuccess = 0;

while ($row = fgetcsv($handle, 0, "\t"))
{
	$numNames++;
	//convert to obj array
	$rowObj = ["index" => ++$rowNum];
	for ($i = 0; $i < count($header); $i++)
	{
		$rowObj[$header[$i]] = trim($row[$i]);
	}
	if (!isset($rowObj["testable"]))
	{
		rowErrPrint($rowObj, "row is not testable");
		continue;
	}
	//skip tests which were marked testable=false
	if (!$rowObj["testable"])
	{
		$numNames--;
		continue;
	}
	if ($currName != $rowObj["name"])
	{
		$currName = $rowObj["name"];
		//same as calling: iventitymatcherhtm/searchEng.php?analyze=yes&returnRawResults=yes&resultType=raw&searchtext=...
		$output = getAnalysis($currName,$ivEntityMatcherService, "raw");
		$xml = simplexml_load_string($output);
		if (!$xml || !$xml->Reply || !$xml->Reply->GetAnalysis || !$xml->Reply->GetAnalysis->OutputParameters)
		{
			rowErrPrint($rowObj, "unexpected xml: $output");
			continue;
		}
		$analysis = $xml->Reply->GetAnalysis->OutputParameters->Analysis;
		//file_put_contents("C:/analysis.xml", $analysis);
		$xml = simplexml_load_string($analysis);
		if ($xml === FALSE)
		{
			rowErrPrint($rowObj, "Failed to load analysis from: $analysis");
			continue;
		}
		$xml->registerXPathNamespace('rdf', 'http://example.org/chapter-title');
		$xml->registerXPathNamespace('iv', $ivPref);
	}
	$xpath = "rdf:Description/iv:" . strtolower($rowObj["slot name"]);
	$values = [];
	$captions = [];
	foreach ($xml->xpath($xpath) as $xpathNode)
	{
		$children = $xpathNode->children("rdf", TRUE);
		//if ($currName == "Ho Chi Min")
		//	print_r($children);
		$rdfResources = [];
		$rdfResource = (string) $xpathNode->attributes("rdf", TRUE)->resource;
		if ($rdfResource)
		{
			$rdfResources[] = $rdfResource;
		}
		if ($children->Seq)
		{
			foreach ($children->Seq->children("rdf", TRUE) as $seq)
			{
				$rdfResources[] = (string) $seq->attributes("rdf", TRUE)->resource;
			}
		}
		else if ($children->count())
		{
			foreach ($children as $child)
			{
				$rdfResource = (string) $child->attributes("rdf", TRUE)->resource;
				if ($rdfResource) $rdfResources[] = $rdfResource;
			}
		}
		if (empty($rdfResources))
		{
			echo "children(???):";
			print_r($children);
			print_r($rdfResources);
		}
		if (empty($rdfResources))
		{
			$values[] = (string)$xpathNode;
		}
		else {
			for ($i = 0; $i < count($rdfResources); $i++)
			{
				$rdfResource = $rdfResources[$i];
				if (strpos($rdfResource, $ivPref) === 0)
				{
					$values[] = str_replace($ivPref . "#", "", $rdfResource);
				}
				{
					$xpath = "rdf:Description[@rdf:about=\"$rdfResource\"]";
					//echo "xpath: $xpath\r\n";
					$xpathArray = $xml->xpath($xpath);
					dbgPrint("xpahArray", $xpathArray);
					foreach ($xpathArray as $instNode)
					{
						dbgPrint("instNode", $instNode);
						dbgPrint("children", $instNode->children("iv", TRUE));
						$caption = (string) $instNode->children("iv", TRUE)->caption;
						$instance = $instNode->children("iv", TRUE)->instance;
						if ($instance)
						{
							//echo "instance.... $instance";
							$rdfResources[] = $instance->attributes("rdf", TRUE)->resource;
						}
						
						if ($caption)
						{
							//echo "capt.... $caption";
							$captions[] = $caption;
						}
						
						foreach ($instNode->children("iv", TRUE) as $child)
						{
							if (!in_array($child->getName(), ["transliteration-ic", "initials"]))
								continue;
							
							$captionValue = (string) $child;
							if ($captionValue)
							{
								//echo "trans: $transliterationIc";
								if (is_array($captionValue))
									foreach ($captionValue as $ti)
										$captions[] = $captionValue;
								else
								$captions[] = $captionValue;
							}
						}
						
						if ($instNode->children("iv", TRUE)->{"name-components"})
						{
							//print_r($instNode->children("iv", TRUE)->{"name-components"}->children("rdf", TRUE)->Seq);
							foreach ($instNode->children("iv", TRUE)->{"name-components"}->children("rdf", TRUE)->Seq->children("rdf", TRUE) as $seq)
							{
								$rdfResources[] = (string) $seq->attributes("rdf", TRUE)->resource;
							}
						}
						//else echo "$rdfResource";//print_r($xpathArray);
					}
					//else echo "not found: $rdfResource";
				}
			}
		}
	}
	
	//dbgPrint("values", $values);
	$foundExpected = false;
	$foundExpectedCaption = false;
	$foundUnexpected = false;
	$foundUnexpectedCaption = false;
	foreach ($values as $value)
	{
		$foundExpected |= strcasecmp($value, $rowObj["value"]) === 0;
		$foundUnexpected |= strcasecmp($value, $rowObj["unexpected value"]) === 0;
	}
	foreach ($captions as $caption)
	{
		$foundExpectedCaption |= strcasecmp(mb_strtolower($caption), mb_strtolower($rowObj["value caption"])) === 0;
		$foundUnexpectedCaption |= strcasecmp(mb_strtolower($caption), mb_strtolower($rowObj["unexpected caption"])) === 0;
	}
	if ($foundUnexpected || $foundUnexpectedCaption)
	{
		rowErrPrint($rowObj, "found unexpected value: $foundUnexpected, caption: $foundExpectedCaption");
		if ($foundUnexpected) print_r($values);
		if ($foundUnexpectedCaption) print_r($captions);
		continue;
	}
	
	if (!empty($rowObj["value"]) && !$foundExpected || 
		!empty($rowObj["value caption"]) && !$foundExpectedCaption)
	{
		rowErrPrint($rowObj, "didn't find expected, value: $foundExpected, caption: $foundExpectedCaption");
		//file_put_contents("rdf.xml", (string) $analysis);
		if (!$foundExpected) print_r($values);
		if (!$foundExpectedCaption) print_r($captions);
		//print_r($rdfResources);
		continue;
	}
	if (!$foundExpected && !$foundExpectedCaption && empty($rowObj["unexpected value"]) && empty($rowObj["unexpected caption"]))
	{
		rowErrPrint($rowObj, "test doesn't have expected/unexpected checks");
		continue;
	}
	
	$numSuccess++;
}
$numFailures = $numNames - $numSuccess;
echo "num names: $numNames, num success: $numSuccess, failures: $numFailures";
//just in case no tests are found at all (which probably indicates a major bug)
if (!$numFailures && !$numSuccess)
	exit(-1);

exit($numFailures);
?>