<?php
/*
 * Display names/codes from Source table and upon selecting one
 * display associated attributes from Dynamic table.
 * Once an attribute from the dynamic table has been selected
 * then display a graph of timestamp and value from the associated DynamicValue
 * table.
 * Allow no more than 10,000 entries to be graphed
 *
 */

require '../Common/openDB.php';
$StdRend = $StandardRendering;
$SelRend = $SelectedRendering;
$NSelRend = $NotSelectedRendering;
$SelRendRight = $SelectedRenderingRight;
$NSelRendRight = $NotSelectedRenderingRight;
$WhiteRend = $StandardRenderingWhite;

$con = mysql_connect($website,$userid,$pw);
if (!$con) {
	die('Could not connect: ' . mysql_error());
}
mysql_query("SET foreign_key_checks = 0",$con);

$curDB = "../CurrentlyOpenedDBName.tmp";
if(file_exists ($curDB)){
	$f = fopen($curDB, "r");
	$dbase   = trim(fgets($f)); // linked database name
	fclose($f);
	mysql_select_db($dbase, $con);
	//echo "Connected to " . $dbase . "<br/>";
}else{
	//No database currently open
	return;
}

$selectionMade = false;
?>

<html>
<head>
   <link rel='stylesheet' type='text/css' href='../CSS/Font.css'>
	<link rel='stylesheet' type='text/css' href='../CSS/TextHiLights.css'>
	<link rel='stylesheet' type='text/css' href='../CSS/HeaderContentFooter.css'>
	<link rel='stylesheet' type='text/css' href='../CSS/Buttons.css'>

	<!-- ALternate lines have different colours except column number 3 which is blank-->
	<style type='text/css'>
		tr:nth-child(2n) > td:nth-child(1){background-color: #f2f2f2;}
		tr:nth-child(2n) > td:nth-child(2){background-color: #f2f2f2;}
		tr:nth-child(2n) > td:nth-child(4){background-color: #f2f2f2;}
		green {
			background-color: green;
			color: black;
		}
		orange {
			background-color: orange;
			color: black;
		}
		red {
			background-color: red;
			color: white;
		}
		table {
			!table-layout: fixed;
			border-collapse: collapse;
			width: 100%;
		}
		td+td+td{width: 200;}
		td+td+td+td{width: 120;}
		td+td+td+td+td{width: 1;}
	</style>

</head>
<body>
	<div id='header'>
		<h4>Time series attributes
<?php if($debug)echo ("<script>  document.write(document.URL); </script>"); ?>
</h4></div>

<?php
$source_id = $_GET[source_id];
$dynamic_id_selected = $_GET[dynamic_id];

echo ("<form method='post'>");
echo ("<div id='content'>");

if($source_id != NULL && $source_id != "add"){
	if($_GET[delete] != NULL){
		$resA = mysql_query("SELECT attribute FROM Dynamic WHERE dynamic_id = {$_GET[delete]}",$con);
		while($rowA = mysql_fetch_array($resA))$nameDyn = $rowA[0];
		$resA = mysql_query("SELECT name FROM Source WHERE source_id = {$source_id}",$con);
		while($rowA = mysql_fetch_array($resA))$nameSrc = $rowA[0];
		delTree("../../Inputs/{$dbase}/{$nameSrc}_{$source_id}/{$nameDyn}_{$_GET[delete]}");

		// delete associated fetcher and frequency as well
		$resA = mysql_query("SELECT fetcher_id FROM Dynamic WHERE dynamic_id={$_GET[delete]}",$con);
		while($rowA = mysql_fetch_array($resA))$fetcher_id = $rowA[0];
		$resA = mysql_query("SELECT frequency_id FROM Fetcher WHERE fetcher_id={$fetcher_id}",$con);
		while($rowA = mysql_fetch_array($resA))$frequency_id = $rowA[0];
		mysql_query("DELETE FROM Frequency WHERE frequency_id={$frequency_id}",$con);
		mysql_query("DELETE FROM Fetcher WHERE fetcher_id={$fetcher_id}",$con);
		mysql_query("DELETE FROM Dynamic WHERE dynamic_id=".$_GET[delete],$con);

		echo ("<a id='#GraphEmpty' href='Graph.php' target='WorkingFrame'></a> ");
		echo("<script>document.getElementById('#GraphEmpty').click();</script>");
		exit;header("Location: Dynamic.php?source_id={$source_id}");
	}

	// Determine if there is any dynamic data associated with selected source
	$DynamicDataPresent = false;
	$result = mysql_query("SELECT count(dynamic_id) FROM Dynamic WHERE source_id=".$source_id.";",$con);
	while($row = mysql_fetch_array($result)){
		if($row[0] > 0){
			$DynamicDataPresent = true;
		}else{
			$DynamicDataPresent = false;
		}
	}

	if($DynamicDataPresent){
		echo("<table width='100%'>");
		echo("<tr><td>
					<button type='submit' {$StdRend} > <b> Tag </b> </button>
				</td>
				<td>
					<button type='submit' {$StdRend} > <b> Value </b> </button>
				</td>
				<td>
				</td>");
		echo("	<td <!--style='float:right'-->
					<button type='submit' {$StdRend} '> <b> Source </b> </button>
				</td>
			</tr>");

		$result = mysql_query("SELECT dynamic_id,attribute,fetcher_id,value,status,fetch_status FROM Dynamic WHERE source_id=".$source_id.";",$con);
		$selectionMade = false;
		while($row = mysql_fetch_array($result)){
			$dynamic_id = $row[0];
			$tag_attribute = $row[1];
			$fetcher_id = $row[2];
			$value = $row[3];
			$status = $row[4];
			$fetch_status = $row[5];
			if($value == NULL)$value = "&nbsp"; // so that complete rectangle shows different colour when selected

			if($fetcher_id == NULL){
				$InputMethod = "&nbsp";
			}else{
				$result1 = mysql_query("SELECT input_method,frequency_id,name,description,EG_fetchpath,EG_fetchfile
										FROM Fetcher WHERE fetcher_id = ".$fetcher_id,$con);
				while ($row1 = mysql_fetch_array($result1)){
					$InputMethod = $row1[0];
					$frequency_id = $row1[1];
					$FetcherName = $row1[2];
					$FetcherDesc = $row1[3];
					$FetchPath = $row1[4];
					$FetchFile = $row1[5];
				}
			}

			// switch fetch status if requested but only for non MDF DID
			$resZ = mysql_query("SELECT MDF_status FROM Dynamic WHERE dynamic_id={$dynamic_id}",$con);
			while($rowZ = mysql_fetch_array($resZ))$MDF_status = trim($rowZ[0]);
			if($MDF_status != "MDF"){
				if($InputMethod != "Manual" && $_GET["switchfetchstatus"] == "yes" && $_GET["dynamic_id"] == $dynamic_id){
					if($fetch_status == "red"){
						mysql_query("UPDATE Dynamic SET fetch_status = 'green'	WHERE dynamic_id={$dynamic_id}",$con);
						$fetch_status = "green";
					}elseif($fetch_status == "green"){
						mysql_query("UPDATE Dynamic SET fetch_status = 'red'	WHERE dynamic_id={$dynamic_id}",$con);
						$fetch_status = "red";
					}else{
						mysql_query("UPDATE Dynamic SET fetch_status = 'green'	WHERE dynamic_id={$dynamic_id}",$con);
						$fetch_status = "green";
					}
				}
			}
			if($fetch_status == "red"){
				$Hilight =  "<HiRed>&nbsp</HiRed>";
			}elseif($fetch_status == "green" || $fetch_status == "NA"){
				$Hilight =  "<HiGreen>&nbsp</HiGreen>";
			}else{
				$Hilight =  "<HiWhite>&nbsp</HiWhite>";
			}
			// Set colour highlights based on input information
			// No colour means there is not enough information to begin fetch
			// Red means there is enough information and to not fetch data when Start is clicked
			// Green means there is enough information and to fetch data when Start is clicked
			if($InputMethod == "Manual"){
				$Hilight =  "<HiWhite>W&nbsp</HiWhite>"; // always white as there is never information required to begin fetch for it

			// File exchange is either green or red depending on whether
			// fetcher information is complete (frequency is specified or not)
			}elseif($InputMethod == "File Exchange"){
				if($frequency_id != NULL){
					$resA = mysql_query("SELECT period,times_per_period FROM Frequency WHERE frequency_id = ".$frequency_id,$con);
					while($rowA = mysql_fetch_array($resA)){
						$period = $rowA[0];
						$timesPP = $rowA[1];
					}
				}

			// Online is	red if fetcher information is incomplete
			//				orange if fetcher information is complete but connection is not tested yet
			//				green if fetcher information is complete and connection has been tested
			}elseif($InputMethod == "Online"){

				// Use proxy for fetcher information
				if($frequency_id != NULL){
					$resA = mysql_query("SELECT period,times_per_period FROM Frequency WHERE frequency_id = ".$frequency_id,$con);
					while($rowA = mysql_fetch_array($resA)){
						$period = $rowA[0];
						$timesPP = $rowA[1];
					}
					if($period == NULL || $timesPP == NULL){
					}else{
						$resA = mysql_query("SELECT EG_source,EG_password,EG_IP,EG_user,description FROM Fetcher WHERE fetcher_id = {$fetcher_id}",$con);
						while($rowA = mysql_fetch_array($resA)){
							$EG_source = $rowA[0];
							$EG_password = $rowA[1];
							$EG_IP = $rowA[2];
							$EG_user = $rowA[3];
							$description = $rowA[4];
						}
						if($EG_source == NULL || $EG_password == NULL || $EG_IP == NULL || $EG_user == NULL){
							mysql_query("UPDATE Fetcher set description = ' ' WHERE fetcher_id = {$fetcher_id}",$con);
						}
					}

				}
			}

			if($frequency_id == NULL){
				$frequency_name = "&nbsp";
			}else{
				$result1 = mysql_query("SELECT name FROM Frequency WHERE frequency_id = ".$frequency_id,$con);
				while($row1 = mysql_fetch_array($result1))$frequency_name = $row1[0];
			}

			echo "<tr>";

			// Display information
			//$selectionMade = false;
			if($_POST[selectedItem] == $dynamic_id || ($_POST[selectedItem] == NULL && $dynamic_id_selected == $dynamic_id)){
				$dynamic_id_selected = $dynamic_id;
				$selectionMade = true;
				$Render = $SelRend;
				$RenderR = $SelRendRight;
			}else{
				$Render = $NSelRend;
				$RenderR = $NSelRendRight;
			}
			echo (
				"<td>".
				"<button type='submit' {$Render} value= '" . $dynamic_id . "' name = 'selectedItem'
				formaction='Dynamic.php?source_id={$source_id}&dynamic_id={$dynamic_id}' > &nbsp" .$tag_attribute. "</button>
				</td>"
			);
			echo(
				"<td>".
				"<button type='submit' {$Render} value= '" . $dynamic_id . "' name = 'selectedItem'
				formaction='Dynamic.php?source_id={$source_id}&dynamic_id={$dynamic_id}' > &nbsp" .$value. "</button>
				</td>"
			);
			echo(
				"<td>
				<!--p {$WhiteRend}>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</p-->
				<button type='submit' {$WhiteRend} value= '" . $dynamic_id . "' name = 'selectedItem'
				formaction='Dynamic.php?source_id={$source_id}&dynamic_id={$dynamic_id}' > " ."&nbsp". "</button>
				</td>"
			);
			if($InputMethod == "Manual"){
				$InputMethodM = "File";
			}elseif($InputMethod == "File Exchange"){
				$InputMethodM = "File";
			}elseif($InputMethod == "Online"){
				$InputMethodM = "Device";
			}
			echo(
				"<td>".
				"<button type='submit' {$Render} value= '" . $dynamic_id . "' name = 'selectInputMethod'
				formaction='Dynamic.php?source_id={$source_id}&dynamic_id={$dynamic_id}' > &nbsp" .$InputMethodM ."</button>
				</td>"
			);
			echo(
				"<td>".
				"<button type='submit' {$RenderR} value= '" . $dynamic_id . "' name = 'selectInputMethod'
				formaction='Dynamic.php?source_id={$source_id}&dynamic_id={$dynamic_id}&switchfetchstatus=yes' > &nbsp" . $Hilight . "</button>
				</td>"
			);

			echo "</tr>";
		}
		echo ("</table>");
		echo ("<input type='hidden' name='source_id' value='".$source_id."'/>");
	}


	echo ("</div>");

	echo ("<div id='footer'>");
	echo ("<button class='btnAdd' type='submit' name='AddRecord' formaction='Dynamic.php?source_id={$source_id}&dynamic_id={$dynamic_id_selected}'>+</button>");
	if(isset($_POST[selectedItem]) || $dynamic_id_selected != NULL){
		echo ("<button class='btnDelete' type='submit' name='DeleteRecord' formaction='Dynamic.php?source_id={$source_id}&delete={$dynamic_id_selected}' >−</button>");
		echo ("<button class='btnEdit' type='submit' name='ViewRecord' formaction='Dynamic.php?source_id={$source_id}&dynamic_id={$dynamic_id_selected}' style='float: right;'>View</button>");
		echo ("<button class='btnEdit' type='submit' name='EditRecord' formaction='Dynamic.php?source_id={$source_id}&dynamic_id={$dynamic_id_selected}' style='float: right;'>Edit</button>");
	}
	echo ("</div>");
}
echo ("</form>");

// Refresh various parts of GUI based on user selection
echo ("<a id='#GraphIt' href='Graph.php?source_id={$source_id}&dynamic_id={$dynamic_id_selected}' target='WorkingFrame'></a> ");
echo ("<a id='#EditRecord' href='AddEditDynamic.php?PK={$dynamic_id_selected}&FK={$source_id}' target='WorkingFrame'></a> ");
echo ("<a id='#AddRecord' href='AddEditDynamic.php?PK=add&FK={$source_id}' ' target='WorkingFrame'></a> ");
echo ("<a id='#Fetcher' href='AddEditFetcher.php?source_id={$source_id}&dynamic_id={$dynamic_id_selected}' ' target='WorkingFrame'></a> ");

if(isset($_POST[ViewRecord]))echo("<script>document.getElementById('#GraphIt').click();</script>");
if(isset($_POST[EditRecord]))echo("<script>document.getElementById('#EditRecord').click();</script>");
if(isset($_POST[AddRecord]))echo("<script>document.getElementById('#AddRecord').click();</script>");
if(isset($_POST[selectInputMethod]))echo("<script>document.getElementById('#Fetcher').click();</script>");
echo ("</body></html>");
?>
