<?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());
}
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;
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 -->
	<style type='text/css'>
      tr:nth-child(2n) {
             background-color: #f2f2f2;
        }
	</style>

</head>
<body>
");

$output_id = $_GET[output_id];
$res = mysql_query("SELECT COUNT(output_id) FROM Output",$con);
while($row = mysql_fetch_array($res))$NumOutputs = $row[0];

// Did user ask to copy?
if($_GET[cpoutput] == "yes"){
	//if($debug)echo ("<script>  document.write(document.URL); </script><br/>");
	if($_GET[cpRI] != "yes" && $_GET[cpRI] != "no"){
		$res = mysql_query("SELECT ranupto FROM Output WHERE output_id = {$_GET[output_id]}",$con);
		while($row = mysql_fetch_array($res))$ran_upto = $row[0];
		if(CurrentlyRunningES($con)){
			echo ("Cannot copy while any service is running, stop before you may copy ");
			echo ("<button type='submit' onclick='javascript:location.href=\"Output.php\"'>OK</button>");
		}elseif($ran_upto != NULL){ // this service has already run ask user if she wants to copy run information as well or not
			echo ("Copy run information?");
			echo ("<button type='submit' onclick='javascript:location.href=\"Output.php?output_id=$output_id&cpoutput=yes&cpRI=yes\"'>Yes</button>");
			echo ("<button type='submit' onclick='javascript:location.href=\"Output.php?output_id=$output_id&cpoutput=yes&cpRI=no\"'>No</button></form><br/>");
			echo 	"This service has already ran in the past. Do you want to copy run information?
					If you select to copy run information the copied service when run will
					start from where the original service has run up to. If you choose to not
					copy run information the copied service when run will start from the
					time the original service ran from when it was first run. <br/>
					If you choose to start service from now in the preferences, then all services
					will run starting from the time the launch service button is pressed.<br/>
					(see manual for further information about when services start from)";
		}
		exit;
	}else{

		// copy output
		$res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Output'",$con);
		while($row = mysql_fetch_array($res))$copied_output_id = $row[0];
		if($_GET[cpRI] == "yes"){
			mysql_query("INSERT INTO Output(name,frequency_id,ranupto,status,es_data_freq_id) SELECT name,frequency_id,ranupto,status,es_data_freq_id FROM Output WHERE output_id =  {$output_id}",$con);
		}else{
			mysql_query("INSERT INTO Output(name,frequency_id,status,es_data_freq_id) SELECT name,frequency_id,status,es_data_freq_id FROM Output WHERE output_id =  {$output_id}",$con);
		}
		//$res = mysql_query("SELECT LAST_INSERT_ID()",$con);

		echo ("Copied output id = " . $copied_output_id);

		// Copy this output and associated scopes and operations
		mysql_query("	INSERT INTO Scope(output_id,attribute,rule,text,master_id)
						SELECT '{$copied_output_id}',attribute,rule,text,master_id
						FROM Scope WHERE output_id = {$output_id}",$con);

		mysql_query("	INSERT INTO Operation(output_id,name,output,selectionA,operation,selectionB)
						SELECT '{$copied_output_id}',name,output,selectionA,operation,selectionB
						FROM Operation WHERE output_id = {$output_id}",$con);
		header("Location: Output.php");
	}
}


echo ("<form method='post'>");
if($NumOutputs > 0){
	echo ("<div id='header'>");
	echo ("<h4>Service");
	if($debug)echo ("<script>  document.write(document.URL); </script>");
	echo ("</h4></div>");
	echo ("<div id='content'>");
	echo ("<table width='100%'>");

	$res = mysql_query("SELECT output_id,name FROM Output",$con);
	while($row = mysql_fetch_array($res)){
		//$name = $row[1];
		//$output_id = $row[0];
		//echo("row[0]=".$row[0]." get_delete = {$_GET[delete]} output_id = {$output_id}<br/>");
		if($_GET[delete] != NULL){
		//if($output_id != NULL && $_GET[delete] == $row[0]){
			//echo("DELETE FROM Output WHERE output_id=".$_GET[delete]);
			$resA = mysql_query("SELECT name FROM Output WHERE output_id=".$_GET[delete],$con);
			while($rowA = mysql_fetch_array($resA))$nameOut = $rowA[0];
			delTree("{$OutputsFolder}/{$dbase}/{$nameOut}");
			rmdir("{$OutputsFolder}/{$dbase}}"); // remove database directory but only if empty
			if($URLOutput){
				delTree("{$OutputWebFolder}/{$dbase}/{$nameOut}");
				rmdir("{$OutputWebFolder}/{$dbase}");
			}
			if($URLOutput2){
				delTree("{$OutputWebFolder2}/{$dbase}/{$nameOut}");
				rmdir("{$OutputWebFolder2}/{$dbase}");
			}
			if($CloudOutput){
				delTree("{$CloudLocation}/{$dbase}/{$nameOut}");
				rmdir("{$CloudLocation}/{$dbase}");
			}
			mysql_query("DELETE FROM Output WHERE output_id=".$_GET[delete],$con);
			mysql_query("DELETE FROM Scope WHERE output_id=".$_GET[delete],$con);
			mysql_query("DELETE FROM Operation WHERE output_id=".$_GET[delete],$con);
			header("Location: Output.php");
		}else{
			echo ("<tr>");
			if($_POST[selectedItem2] == $row[0] || $output_id == $row[0]){
				$output_id = $_POST[selectedItem2];
				$Render = $SelRend;
			}else{
				$Render = $NSelRend;
			}
			echo (	"<td>".
				"<button type='submit' {$Render} value= '" . $row[0] . "' name = 'selectedItem2'
				formaction='Output.php?output_id={$row[0]}' > " .$row[1]. "</button>
				</td>");
			echo ("</tr>");
		}
	}
	echo("</table>");
}
echo "</div>";
echo ("<div id='footer'>");
echo ("<button class='btnAdd' type='submit' name='AddRecord' formaction='Output.php'>+</button>");
if($output_id != NULL){
	echo ("<button class='btnEdit' type='submit' name='EditRecord' formaction='Output.php?output_id=$output_id&PK=$_POST[selectedItem2]' style='float: right;'>Edit</button>");
	echo ("<button class='btnEdit' type='submit' name='CopyRecord' formaction='Output.php?output_id=$output_id&cpoutput=yes' style='float: right;'>Copy</button>");
	echo "<button class='btnDelete' type='submit' value= '" . $row[0] . "' name = 'delete'
		formaction='Output.php?delete=$output_id' >-</button>";
}
echo ("</div>");
echo ("</form>");

// Redirect execution based on JS
echo ("<a id='#AddRecord' href='#' onClick=\" window.open('AddEditOutput.php?output_id=add','MyWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=yes,width=600,height=700') \"></a> ");
echo ("<a id='#EditRecord' href='#' onClick=\" window.open('AddEditOutput.php?output_id={$_GET[output_id]}','MyWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=yes,width=600,height=700') \"></a> ");
echo ("<a id='#Scope' href='Scope.php?output_id=$output_id' target='ScopeFrame'></a> ");
echo ("<a id='#Operation' href='Operation.php?output_id=$output_id' target='OperationFrame'></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[CopyRecord]))echo("<script>document.getElementById('#CopyRecord').click();</script>");
if($output_id != "add"){
	echo("<script>document.getElementById('#Scope').click();</script>");
	echo("<script>document.getElementById('#Operation').click();</script>");
}
echo ("</body></html>");
?>
