<?php
require '../Common/openDB.php';
$StdRend = $StandardRendering;
$SelRend = $SelectedRendering;
$NSelRend = $NotSelectedRendering;
$con = mysql_connect($website,$userid,$pw);
if(!$con)die('Could not connect: ' . mysql_error());

$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;
}
mysql_query("SET foreign_key_checks = 0",$con);
$selectionMade = false;
echo ("
<html>
<head>
  <link rel='stylesheet' type='text/css' href='../CSS/Font.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 4 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(3){background-color: #f2f2f2;}
    tr:nth-child(2n) > td:nth-child(5){background-color: #f2f2f2;}
    tr:nth-child(2n) > td:nth-child(6){background-color: #f2f2f2;}
  </style>
</head>
<body>
");

// Get output_id if specified
$output_id = $_GET[output_id];
$operation_id=$_GET[operation_id];

$res = mysql_query("SELECT COUNT(operation_id) FROM Operation",$con);
while($row = mysql_fetch_array($res))$NumOperations = $row[0];

echo ("<form method='post'>");
echo ("<div id='header'>");
echo ("<h4>Service definition");
if($debug)echo ("<script>  document.write(document.URL); </script>");
echo ("</h4></div>");
echo ("<div id='content'>");
if($NumOperations > 0){
  echo ("<table width='100%'>");
  if($output_id != NULL){
		$res = mysql_query("SELECT count(operation_id) FROM Operation WHERE output_id={$output_id}",$con);
		while($row = mysql_fetch_array($res))$NumOpsWithThisFK = $row[0];
		if($NumOpsWithThisFK > 0){
		if($GeekMode){
			$str1 = "Operand 1"; $str2 = "Operation"; $str3 = "Operand 2";
			$str1 = "Selection"; $str2 = "Action"; $str3 = "Supplement";
		}else{
			$str1 = "Selection"; $str2 = "Action"; $str3 = "Supplement";
		}
		echo ("
		<tr>
			<td>
				<button type='submit' {$StdRend} > <b> {$str1}</b> </button>
			</td>
			<td>
				<button type='submit' {$StdRend} > <b> {$str2}</b> </button>
			</td>
			<td>
				<button type='submit' {$StdRend} > <b> {$str3}</b> </button>
			</td>
			<td>&nbsp;&nbsp;</td>
			<td>
				<button type='submit' {$StdRend} > <b> Result </b> </button>
			</td>
			<td>
				<button type='submit' {$StdRend} > <b> Output </b> </button>
			</td>
			</tr>"); 					//       0           1     2        3         4          5
		$res = mysql_query("SELECT operation_id,name,selectionA,operation,selectionB,output FROM Operation WHERE output_id={$output_id}",$con);
			while($row = mysql_fetch_array($res)){
				if($_GET[delete] != NULL){
					mysql_query("DELETE FROM Operation WHERE operation_id=".$_GET[delete],$con);
					header("Location: Operation.php?output_id={$output_id}");
				}else{
					// Get operand name and help
					$operA = get_operand_name($con,$row[2],"name");
					$operB = get_operand_name($con,$row[4],"name");
					$operation_help = get_operation_help($row[3]);
					$operA_help = get_operand_name($con,$row[2],"help");
					$operB_help = get_operand_name($con,$row[4],"help");

					echo ("<tr>");
					// Debug session following bug provided by JA in that output 1 is always selected
					//if($_POST[selectedItem2] == $row[0] || $output_id == $row[0]){
					if($_POST[selectedItem2] == $row[0]){
						$operation_id = $_POST[selectedItem2];
						$Render = $SelRend;
					}else{
						$Render = $NSelRend;
					}
					echo (	"<td>".
						"<button type='submit' {$Render} value= '{$row[0]}' name = 'selectedItem2' title='{$operA_help}'
						formaction='Operation.php?operation_id={$row[0]}&output_id={$output_id}' >{$operA}</button>
						</td>");
					echo (	"<td>".
						"<button type='submit' {$Render} value= '" . $row[0] . "' name = 'selectedItem2' title='{$operation_help}'
						formaction='Operation.php?operation_id={$row[0]}&output_id={$output_id}' >" .$row[3]. "</button>
						</td>");
					echo (	"<td>".
						"<button type='submit' {$Render} value= '{$row[0]}' name = 'selectedItem2' title='{$operB_help}'
						formaction='Operation.php?operation_id={$row[0]}&output_id={$output_id}' >{$operB}</button>
						</td>");
					echo ("<td></td>");

					$title = "Name of the parameter resulting from this action (optional)";
					if($row[5]== "if true" || $row[5] == "if false"){
						$OID_to_list = get_conditional_OID($operation_id,$con);
					}
					echo (	"<td>".
						"<button type='submit' {$Render} value= '" . $row[0] . "' name = 'selectedItem2' title='{$title}'
						formaction='Operation.php?operation_id={$row[0]}&output_id={$output_id}' >" .$row[1]. "</button>
						</td>");

					$title = "Is this parameter to be written to the output file?";
					if($row[5]== "if true"){
							$title = "Results listed in the previous column will be output if the condition is true";
					}elseif($row[5]== "if false"){
							$title = "Results listed in the previous column will be output if the condition is false";
					}
					echo (	"<td>".
						"<button type='submit' {$Render} value= '" . $row[0] . "' name = 'selectedItem2' title='{$title}'
						formaction='Operation.php?operation_id={$row[0]}&output_id={$output_id}' >" .$row[5]. "</button>
						</td>");
					echo ("</tr>");
				}
			}
		}
	}
	echo("</table>");
}
if(isset($_POST[validate])){
	echo "<br/>Validation facility is still under development<br/>";
	exit;
}

echo "</div>";
echo ("<div id='footer'>");
if($output_id != NULL){
	echo ("<button class='btnAdd' type='submit' name='AddRecord' formaction='Operation.php?output_id=$output_id'>+</button>");
	if($operation_id != NULL){
		echo "<button class='btnDelete' type='submit' value= '" . $row[0] . "' name = 'delete'
			formaction='Operation.php?delete=$operation_id&output_id=$output_id' >−</button>";
	}
	echo ("<button class='btnAdd' type='submit' name = 'validate' style='float: right;' formaction='Operation.php?output_id=$output_id'>Validate</button>");

	echo ("<div style='float: right;'>");
	$res = mysql_query("SELECT count(frequency_id) FROM Output WHERE output_id = {$output_id}",$con);
	while($row = mysql_fetch_array($res))$count = $row[0];
	if($count <= 0){

	}else{
		$res = mysql_query("SELECT frequency_id FROM Output WHERE output_id = {$output_id}",$con);
		while($row = mysql_fetch_array($res))$frequency_id = $row[0];
		$res = mysql_query("SELECT count(name) FROM Frequency WHERE frequency_id = {$frequency_id}",$con);
		while($row = mysql_fetch_array($res))$NumFreqName = $row[0];
		if($NumFreqName == 0){
			$FreqName = "Select Service Frequency";
		}else{
			$res = mysql_query("SELECT name FROM Frequency WHERE frequency_id = {$frequency_id}",$con);
			while($row = mysql_fetch_array($res))$FreqName = "Service Frequency: " . $row[0];
		}
	}

	$res = mysql_query("SELECT count(es_data_freq_id) FROM Output WHERE output_id = {$output_id}",$con);
	while($row = mysql_fetch_array($res))$data_count = $row[0];
	if($data_count <= 0){

	}else{
		$res = mysql_query("SELECT es_data_freq_id FROM Output WHERE output_id = {$output_id}",$con);
		while($row = mysql_fetch_array($res))$data_freq_id = $row[0];
		$res = mysql_query("SELECT count(name) FROM Frequency WHERE frequency_id = {$data_freq_id}",$con);
		while($row = mysql_fetch_array($res))$NumFreqName = $row[0];
		if($NumFreqName == 0){
			$ServDataFreqName = "Select Data Processing Frequency";
		}else{
			$res = mysql_query("SELECT name FROM Frequency WHERE frequency_id = {$data_freq_id}",$con);
			while($row = mysql_fetch_array($res))$ServDataFreqName = "Calculation Frequency: " . $row[0];
		}
	}

	if($operation_id != NULL){
		echo ("<button class='btnEdit' type='submit' name='EditRecord' formaction='Operation.php?output_id=$output_id&operation_id=$_POST[selectedItem2]' style='float: right;'>Edit</button>");
	}
	echo ("&nbsp &nbsp &nbsp &nbsp &nbsp ");
	if($count > 0){
		echo ("<button class='btnFrequency' type='submit' name='EditFrequency' value='{$FreqName}' formaction='Operation.php?output_id=$output_id&frequency_id={$frequency_id}' style='float: right;'>{$FreqName}</button>");
	}else{
		echo ("<button class='btnNoFrequency' type='submit' name='EditFrequency' value='Associate Service Run Frequency' formaction='Operation.php?output_id=$output_id&frequency_id=add' style='float: right;'>Associate Service Run Frequency</button>");
	}
	if(!$DemoMode){
		if($data_count > 0){
			echo ("<button class='btnFrequency' type='submit' name='EditServDataFreq' value='{$ServDataFreqName}' formaction='Operation.php?output_id=$output_id&frequency_id={$data_freq_id}&data_freq=yes' style='float: right;'>{$ServDataFreqName}</button>");
		}else{
			echo ("<button class='btnNoFrequency' type='submit' name='EditServDataFreq' value='Associate Data Processing Frequency' formaction='Operation.php?output_id=$output_id&data_freq_id=add' style='float: right;'>Associate Data Processing Frequency</button>");
		}
	}
	echo ("</div>");
}
echo ("</div>");
echo ("</form>");

// Redirect execution based on JS
echo ("<a id='#AddRecord' href='#' onClick=\" window.open('AddEditOperation.php?output_id={$output_id}&operation_id=add','MyWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=yes,width=600,height=400') \"></a> ");
echo ("<a id='#EditRecord' href='#' onClick=\" window.open('AddEditOperation.php?output_id={$output_id}&operation_id={$operation_id}','MyWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=yes,width=600,height=400') \"></a> ");
echo ("<a id='#EditFrequency' href='#' onClick=\" window.open('Frequency.php?output_id={$output_id}&frequency_id={$frequency_id}','MyWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=yes,width=600,height=400') \"></a> ");
echo ("<a id='#EditServDataFreq' href='#' onClick=\" window.open('Frequency.php?output_id={$output_id}&frequency_id={$data_freq_id}&data_freq=yes','MyWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=yes,width=600,height=400') \"></a> ");

if(isset($_POST[AddRecord]))echo("<script>document.getElementById('#AddRecord').click();</script>");
if(isset($_POST[EditRecord]))echo("<script>document.getElementById('#EditRecord').click();</script>");
if(isset($_POST[EditFrequency]))echo("<script>document.getElementById('#EditFrequency').click();</script>");
if(isset($_POST[EditServDataFreq]))echo("<script>document.getElementById('#EditServDataFreq').click();</script>");

echo ("</body></html>");

function get_operation_help($oper){
	if($oper == "+"){
		return "Find sum of. Supplemental scoped item required.";
	}elseif($oper == "-"){
		return "Find difference of. Supplemental scoped item required.";
	}elseif($oper == "*"){
		return "Find difference of. Supplemental scoped item required.";
	}elseif($oper == "/"){
		return "Find fraction of. Supplemental scoped item required.";
	}elseif($oper == "Equals"){
		return "Return true if selection and supplement are exactly the same. Supplemental scoped item required.";
	}elseif($oper == ">"){
		return "Greater than. Supplemental scoped item required.";
	}elseif($oper == ">="){
		return "Greater than or equal to. Supplemental scoped item required.";
	}elseif($oper == "<"){
		return "Less than. Supplemental scoped item required.";
	}elseif($oper == "<="){
		return "Less than or equal to. Supplemental scoped item required.";
	}elseif($oper == "AND"){
		return "Logical AND. Supplemental scoped item required.";
	}elseif($oper == "OR"){
		return "Logical OR. Supplemental scoped item required.";
	}elseif($oper == "List"){
		return "List scoped items. Supplemental scoped item not required.";
	}elseif($oper == "Count"){
		return "Return a single number for every occurance of scoped item. Supplemental scoped item not required.";
	}elseif($oper == "List (raw)"){
		return "List scoped items but with time stamps as originally recorded. Supplemental scoped item not required.";
	}elseif($oper == "Count (raw)"){
		return "Return a single number for every occurance of scoped item but with time stamps as originally recorded. Supplemental scoped item not required.";
	}elseif($oper == "Integrate"){
		return "Return a single number for every occurance of scoped item equal to the time integral. Supplemental scoped item not required.";
	}elseif($oper == "Sum"){
		return "Return a single number for every occurance of scoped item equal to the sum of all values over the service frequency. Supplemental scoped item not required.";
	}elseif($oper == "Mean"){
		return "Return a single number for every occurance of scoped item equal to the mean. Supplemental scoped item not required.";
	}elseif($oper == "Maximum"){
		return "Return a single number for every occurance of scoped item equal to the maximum. Supplemental scoped item not required.";
	}elseif($oper == "Minimum"){
		return "Return a single number for every occurance of scoped item equal to the minimum. Supplemental scoped item not required.";
	}elseif($oper == "Median"){
		return "Return a single number for every occurance of scoped item equal to the median. Supplemental scoped item not required.";
	}elseif($oper == "Mode"){
		return "Return a single number for every occurance of scoped item equal to the mode, for multimodal distributions return more than one mode. Supplemental scoped item not required.";
	}elseif($oper == "NOT"){
		return "Logical NOT. Supplemental scoped item not required.";
	}elseif($oper == "Standard deviation"){
		return "Return a single number for every occurance of scoped item equal to the standard deviation. Supplemental scoped item not required.";
	}elseif($oper == "5th percentile"){
		return "Return a single number for every occurance of scoped item equal to the 5th percentile. Supplemental scoped item not required.";
	}elseif($oper == "10th percentile"){
		return "Return a single number for every occurance of scoped item equal to the 10th percentile. Supplemental scoped item not required.";
	}elseif($oper == "25th percentile"){
		return "Return a single number for every occurance of scoped item equal to the 25th percentile. Supplemental scoped item not required.";
	}elseif($oper == "75th percentile"){
		return "Return a single number for every occurance of scoped item equal to the 75th percentile. Supplemental scoped item not required.";
	}elseif($oper == "90th percentile"){
		return "Return a single number for every occurance of scoped item equal to the 90th percentile. Supplemental scoped item not required.";
	}elseif($oper == "95th percentile"){
		return "Return a single number for every occurance of scoped item equal to the 95th percentile. Supplemental scoped item not required.";
	}else{
		return "";
	}

}

?>
