<?php
//require_once 'loginCheckPoint.php';
require_once 'parseUtils.php';

if ($argv[1] != "invokedFromBatch")
	die("This operation cannot be invoked.");

$mysqli = sqlCreateConnection("extractScoringAnnotations");
$res_filenames = sqlQuery($mysqli, "SELECT filename,groupname,`name`,docid FROM files,filetags WHERE files.id=filetags.docid ORDER BY files.id,groupname");

if (!$res_filenames)
{
	print "ERROR! failed to select files";
	die();
}

// "Create" the document.
$xml = new DOMDocument( "1.0", "WINDOWS-1252" );
//echo print_r($res_filenames, TRUE);

// Create some elements.
$xml_training = $xml->createElement( "Training" );
$xml_files    = $xml->createElement( "Files" );
$filename     = 0;
$xml_file     = 0;
$xml_scores   = 0;
$xml_referee  = 0;
while ($row = $res_filenames->fetch_object())
{
	$newFile= ($row->filename == $filename)?0:1;
	$filename = $row->filename;
	$filepath= docIdToOrigFolder($row->docid, $mysqli) . "\\" . $filename;
	if($newFile) {
		$xml_file    = $xml->createElement( "File" );
		$xml_file->setAttribute("fileName", $filepath );
		$xml_file->setAttribute("handled", "true" );
		$xml_scores  = $xml->createElement( "Scores" );
		$xml_referee = $xml->createElement( "Referee" );
		$xml_scores->appendChild( $xml_referee );
		$xml_file  ->appendChild( $xml_scores );
		$xml_files ->appendChild( $xml_file );
	}
	$cluster = $row->groupname;
	$categry = $row->name;
	$xml_score = $xml->createElement( "Score" );
	$xml_score->setAttribute("score"    , $categry);
	$xml_score->setAttribute("scoreName", $cluster);
	$xml_referee->appendChild($xml_score);
}

$xml_training->appendChild( $xml_files );
$xml->appendChild( $xml_training );

// Parse the XML.
if(!$_GET['isFile'] && empty($argv[1])) {
	// Set the content type to be XML, so that the browser will   recognise it as XML.
	header( "content-type: application/xml; charset=WINDOWS-1252" );
	print $xml->saveXML();
}else{
	$dump = $xml->saveXML();
	file_put_contents("tmp/training.xml",$dump);
	print "saved to file!";
}


?>