<?php

require '../2_Projects/FileOperations.php';
require '../Common/preferences.php';

$StdRend = $StandardRendering;
$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;
}

$dynamic_id = $_GET[dynamic_id];
$source_id = $_GET[source_id];
$debug_local = false;
$debug_local = true;

// get fetcher record linked with this dynamic_id (it should have been linked when this dynamic_id was created)
$i = 0;
$fetcher_id = NULL;
$res = mysql_query("SELECT COUNT(fetcher_id) FROM Dynamic WHERE dynamic_id={$dynamic_id}",$con);
while($row = mysql_fetch_array($res))$i = $row[0];
if($i > 0){
	$res = mysql_query("SELECT fetcher_id,MDF_status FROM Dynamic WHERE dynamic_id={$dynamic_id}",$con);
	while($row = mysql_fetch_array($res)){
		$fetcher_id = $row[0];
		$MDF_status = $row[1];
	}
}else{
	echo ("No fetcher linked with dynamic attribute with id {$dynamic_id} the database has been ill defined ");
	echo ("delete this attribute");
	exit;
}
?>

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").toggle();
    });
});
</script>
</head>
<body>

<?php

if($debug)echo ("<script>  document.write(document.URL); </script>");

if($_GET[act] == "fileX" || $_GET[act] == "online"){
	echo ("<a id='#Return' href='../Common/BlankPage.html' target='WorkingFrame'></a> ");
	echo ("<a id='#Reload1' href='Dynamic.php?source_id={$source_id}&dynamic_id={$dynamic_id}' target='DynamicFrame'></a> ");
	echo ("<a id='#Reload2' href='Source.php?source_id={$source_id}&loadothers=no' target='SourceFrame'></a> ");

	if(isset($_POST[NotUpdateTable])){
		echo("<script>document.getElementById('#Return').click();</script>");
	}
	if(isset($_POST[UpdateTable])){
		// get frequency_id if specified previously or create new frequency_id
		$i = 0;
		$frequency_id = NULL;
		$res = mysql_query("SELECT COUNT(frequency_id) FROM Fetcher WHERE fetcher_id = {$fetcher_id}",$con);
		while($row = mysql_fetch_array($res))$i = $row[0];
		if($i > 0){
			$res = mysql_query("SELECT frequency_id FROM Fetcher WHERE fetcher_id = {$fetcher_id}",$con);
			while($row = mysql_fetch_array($res))$frequency_id = $row[0];
		}else{
			mysql_query("DELETE FROM Frequency WHERE name='dynamic_id {$dynamic_id}'");
			$res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Frequency'",$con);
			mysql_query("INSERT INTO Frequency(name) VALUES('dynamic_id {$dynamic_id}')",$con);

			//$res = mysql_query("SELECT LAST_INSERT_ID()",$con);
			while($row = mysql_fetch_array($res))$frequency_id = $row[0];
			mysql_query("UPDATE Fetcher SET frequency_id={$frequency_id} WHERE fetcher_id={$fetcher_id}",$con);
		}

		if($frequency_id == NULL){
			echo ("No frequency linked with dynamic attribute with id {$dynamic_id} the database has been ill defined ");
			echo ("delete this attribute");
			exit;
		}

		// Now that fetcher_id and frequency_id have been determined update records
		// Update Fetcher first
		$AppDest = $_POST[AppDestinationLocal];
		$UnixAppDestLocal = trim($AppDest);
		$AppDest = $_POST[AppDestinationRemote];
		$UnixAppDestRemote = trim($AppDest);

		// Fetch file and fetch path are no longer supported and part of the database schema as
		// standard locations on the EnTrak system are used (EnTrak/Inputs/FileX/dbname/source_name_$SID/dynamic_attribute_name_$DID)
		/*
		$FileNameAndPath = $_POST[FileNameAndPath];
		$UnixFileNameAndPath = str_replace("\\","/",$FileNameAndPath);
		$Path = $FileNameAndPath;
		$file = strrchr($UnixFileNameAndPath,'/'); // get string after last / character
		$Path = rtrim($UnixFileNameAndPath,$file) . "/"; // remove trailing $file but leave file separator /
		$Path = rtrim($Path,'\\'); // remove trailing $file
		$file = ltrim($file, '/'); // remove leading /
		*/
		//echo ('Unchanged = '.$FileNameAndPath.' <br/>');
		//echo ('Replaced = '.$UnixFileNameAndPath.' <br/>');
		//echo ('File name = ' .$file .'<br/>');
		//echo ('Path name = ' .$Path .'<br/>');

		// Add information common to fileX and online
		mysql_query("UPDATE Fetcher SET name='dynamic_id {$dynamic_id}',
										EG_appdestinationLocal='{$UnixAppDestLocal}',
										EG_appdestinationRemote='{$UnixAppDestRemote}',
										frequency_id={$frequency_id}
									WHERE fetcher_id={$fetcher_id}",$con);


		// Add information exclusive to fileX and online
		if($_GET[act] == "fileX"){
			mysql_query("UPDATE Fetcher SET EG_source = 'file'	WHERE fetcher_id={$fetcher_id}",$con);
		}elseif($_GET[act] == "online"){
			if($_POST[source] == "ftp"){
				$source = "ftp";
			}else{
				$source = "LRS";
			}
		}
		mysql_query("UPDATE Fetcher SET EG_source = '{$source}',
											EG_user = '{$_POST[username]}',
											EG_password = '{$_POST[password]}',
											EG_IP = '{$_POST[IPAddress]}',
											EG_destination = '{$_POST[SensorCode]}',
											expected_data_items = '{$_POST[num_items]}'
									WHERE fetcher_id={$fetcher_id}",$con);

		// Now update Frequency table
		//echo ("Frequency is every {$_POST[Frequent]} {$_POST[TimeSpan]}");
		$period = $_POST[TimeSpan];
		$times_per_period = $_POST[Frequent];

		/*
		$timesX = $_POST[Frequent];
		$periodX = $_POST[TimeSpan];
		if($periodX == "Minute(s)"){
			$period = "Hour";
			$times_per_period = NULL;
			if($timesX != 0 && $timesX != "0")$times_per_period = 60 / $timesX;
		}elseif($periodX == "Hour(s)"){
		echo ("<option>Hour(s)</option>");
		echo ("<option>Day(s)</option>");
		echo ("<option>Week(s)</option>");
		echo ("<option>Month(s)</option>");
		}
		*/
		$start_time_day = $_POST[start_hour] . ":" . $_POST[start_minute];
		$stop_time_day = $_POST[stop_hour] . ":" . $_POST[stop_minute];
		if(count($_POST[day_of_week]) > 0)foreach($_POST[day_of_week]  as $str)$dow .= $str . ",";
		if($start_time_day == ":")$start_time_day = "";
		if($stop_time_day == ":")$stop_time_day = "";
		if($dow == ",")$dow = "";
		$dom = $_POST[day_of_month];
		//if(count($_POST[day_of_month])> 0)foreach($_POST[day_of_month] as $str)$dom .= $str . ",";

		//echo("start hour = {$_POST[start_hour]}<br/>");
		//echo("start minute = {$_POST[start_minute]}<br/>");
		//echo("stop hour = {$_POST[stop_hour]}<br/>");
		//echo("stop minute = {$_POST[stop_minute]}<br/>");
		//echo("D O Week = {$dow}<br/>");
		//echo("D O Month = {$dom}<br/>");

		mysql_query("UPDATE Frequency SET period='{$period}',
											times_per_period='{$times_per_period}',
											sta_tm_day = '{$start_time_day}',
											end_tm_day = '{$stop_time_day}',
											day_o_week = '{$dow}',
											day_o_mnth = '{$dom}'
									WHERE frequency_id = '{$frequency_id}'",$con);
		echo("<script>document.getElementById('#Reload2').click();</script>");
		echo("<script>document.getElementById('#Reload1').click();</script>");
		echo("<script>document.getElementById('#Return').click();</script>");
	}


}elseif($_GET[act] == "upload1of2"){
	//Ask for and read a csv file, then input the data into dynamicvalue
	echo("<form action='AddEditFetcher.php?act=upload2of2&dynamic_id={$dynamic_id}' method='post' enctype='multipart/form-data'>");
	echo("<input type='file' name='fileToUpload' accept='.csv' style='font-family:ariel; font-size:100%;'/>");
	echo("<input type='submit' name='Upload' value='Upload' />");
	echo("</form>");
	exit;


}elseif($_GET[act] == "upload2of2"){

	$target_file = basename($_FILES["fileToUpload"]["name"]);
	$upload = true;
	if ($_FILES["fileToUpload"]["size"] > $max_file_size_manual_upload) {
		WarnUser("Sorry, your file is too large. <br/>Maximum size allowed is {$max_file_size_manual_upload}Bytes", "../Projects.html");
		$upload = false;
		exit;
	}else{
		if($debug_local)echo "Size okay for file " . $_FILES["fileToUpload"]["name"];
	}

	if($upload){
		if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$target_file)){
			if($debug_local)echo "File uploaded successfully as $target_file<br />";
			$success = true;
			chmod($target_file,0777);
		}else{
			if($debug_local)echo("move_uploaded_file(".$_FILES["fileToUpload"]["tmp_name"].",".$target_file.")</br>");
			$success = false;
			WarnUser("There was an error in file upload", "../Common/BlankPage.html");
			exit;
		}
	}

	// Read data in the file into database
	if($success){
		$f = fopen($target_file,"r") or die ("Unable to open file");
		ini_set('max_execution_time', $max_exe_time);

		// Set execution time to be infinity as a large file will need more time
		//set_time_limit(0);
		$ii = 0;
		while(!feof($f)) {
			ini_set("auto_detect_line_endings", true);
			$ii++;
			$data = explode(',',fgets($f));

			mysql_query("SET foreign_key_checks = 0",$con);

			mysql_query("INSERT INTO DynamicValue(dynamic_id,timestamp,value) VALUES({$dynamic_id},{$data[0]},{$data[1]})",$con);
			if($debug_local)echo("INSERT INTO DynamicValue(dynamic_id,timestamp,value)  VALUES({$dynamic_id},{$data[0]},{$data[1]})<br/>");
			//if($debug_local)echo ("Item one {$data[0]} Item two {$data[1]} <br/>");
			if($ii % 100 == 0 && $debug_local){
				$records += 100;
				echo "Uploaded {$records} records <br/>";
			}
		}
		echo("All values read in to database");
		exec("DEL /F/Q \"$target_file\"");
	exit;
	}
}

// Get input_method if user has already defined it
$input_method="";
$i = 0;
$res = mysql_query("SELECT COUNT(fetcher_id) from Dynamic WHERE dynamic_id={$dynamic_id}",$con);
while($row=mysql_fetch_array($res))$i=$row[0];
if($i > 0){
	$res = mysql_query("SELECT fetcher_id from Dynamic WHERE dynamic_id={$dynamic_id}",$con);
	while($row=mysql_fetch_array($res))$fetcher_id=$row[0];

	$res = mysql_query("SELECT COUNT(input_method) FROM Fetcher WHERE fetcher_id={$fetcher_id}",$con);
	while($row=mysql_fetch_array($res))$ii=$row[0];

	if($ii > 0){
		$res = mysql_query("SELECT input_method FROM Fetcher WHERE fetcher_id={$fetcher_id}",$con);
		while($row=mysql_fetch_array($res))$input_method=$row[0];
	}

	$res = mysql_query("SELECT COUNT(frequency_id) FROM Fetcher WHERE fetcher_id={$fetcher_id}",$con);
	while($row=mysql_fetch_array($res))$ii=$row[0];

	if($ii > 0){
		$res = mysql_query("SELECT frequency_id FROM Fetcher WHERE fetcher_id={$fetcher_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))$iii=$row[0];
		if($iii > 0){
			$res = mysql_query("SELECT name FROM Frequency WHERE frequency_id={$frequency_id}",$con);
			while($row=mysql_fetch_array($res))$frequency_name=$row[0];
		}
	}
}

if($input_method == ""){
	echo("Input method has not been defined, click edit in the time series panel");
	exit;
}elseif($input_method == "Manual"){
	echo("<form action='GenManualTemplate.php' method='post' >");
	echo("<table>");
	//<button type='submit' {$StdRend} > <b> Tag </b> </button>

	echo("<tr>");
		echo("<td>");
			echo("<font size='2'>Start time</font>");
		echo("</td>");
		echo("<td>");
			echo("<input type='text' autocomplete='off' name='StartTime' size = '60' placeholder='YYYY-MM-DD [hh:mm:ss]' />");
		echo("</td>");
	echo("</tr>");

	echo("<tr>");
		echo("<td>");
			echo("<font size='2'>Stop time</font>");
		echo("</td>");
		echo("<td>");
			echo("<input type='text' autocomplete='off' name='StopTime' size = '60' placeholder='YYYY-MM-DD [hh:mm:ss]' />");
		echo("</td>");
	echo("</tr>");

	echo("<tr>");
		echo("<td>");
			echo("<font size='2'>Time step");
		echo("</td>");
		echo("<td>");
			echo("<input type='text' autocomplete='off' name='TimeStep' size = '20' />  <font size='2'>times every </font>");
			echo ("<select name='Period'>");
			echo ("<option>Minute</option>");
			echo ("<option>Hour</option>");
			echo ("</select>");
		echo("</td>");
	echo("</tr>");
	echo("</table>");

	echo("<input type='submit' value='Generate template'/>");
	echo("<input type='submit' value='Read data' formaction='AddEditFetcher.php?act=upload1of2&dynamic_id={$dynamic_id}'/>");
	echo("</form>");
	exit;

// Write form information if previously entered to display to user
}elseif($input_method == "File Exchange" || $input_method == "Online" || $MDF_status == "MDF"){
	$FileNameAndPath 	= NULL;
	$frequency_id 		= NULL;
	$EG_source 			= NULL;
	$EG_user 			= NULL;
	$EG_password 		= NULL;
	$EG_IP 				= NULL;
	$EG_fetchfile 		= NULL;
	$EG_fetchpath 		= NULL;
	$period 			= NULL;
	$times_per_period 	= NULL;
	$everyXMin			= NULL;
	$ftpSel				= NULL;
	$ipSel				= NULL;
	$EG_appdestinationLocal 	= NULL;
	$EG_appdestinationRemote 	= NULL;

	$res = mysql_query("SELECT * FROM Fetcher WHERE fetcher_id = {$fetcher_id}",$con);
	while ($row = mysql_fetch_array($res)){
		$fetcher_name = $row[1];
		$frequency_id = $row[4];
		$EG_source = $row[5];
		$EG_user = $row[6];
		$EG_password = $row[7];
		$EG_destination = $row[8];
		$EG_appdestinationLocal = $row[9];
		$EG_appdestinationRemote = $row[10];
		$EG_IP = $row[11];
		$EG_fetchfile = $row[13];
		$EG_fetchpath = $row[14];
		$num_items_exp = $row[18];
		if(!$DemoMode && $fetcher_name == "dynamic_id "){
			$num_items_exp = 1; // for visualisation purposes only
		}
	}
	// $FileNameAndPath = $EG_fetchpath . "/" . $EG_fetchfile;
	// if($FileNameAndPath == "/")$FileNameAndPath = NULL;
	$FileNameAndPath = $EG_fetchpath . $EG_fetchfile;
	if($EG_source == "ftp"){
		$ftpSel = "selected";
	}elseif($EG_source == "LRS"){
		$ipSel = "selected";
	}
	if(gettype($frequency_id) == "string"){
		$res = mysql_query("SELECT * FROM Frequency WHERE frequency_id = {$frequency_id}",$con);
		while ($row = mysql_fetch_array($res)){
			$period = $row[2];
			$times_per_period = $row[3];
			$start_time = $row[4];
			$stop_time = $row[5];
			$start_time_day = $row[6];
			$stop_time_day = $row[7];
			$day_of_week = $row[8];
			$day_of_month = $row[9];
		}

		$sel_min = "";
		$sel_hr = "";
		$sel_day= "";
		$sel_wk = "";
		$sel_mnth = "";
		if($period == "MINUTE"){
			$sel_min = "selected";
		}elseif($period == "HOURLY"){
			$sel_hr = "selected";
		}elseif($period == "DAILY"){
			$sel_day= "selected";
		}elseif($period == "WEEKLY"){
			$sel_wk = "selected";
		}elseif($period == "MONTHLY"){
			$sel_mnth = "selected";
		}elseif($period == "" || $period = NULL){
			//continue;
		}else{
			echo ("<h3> old format frequency defined please delete and redefine </h3>");
		}

		// << temporary fix sort the following code later >>
		if($period == "Hour" && $times_per_period != 0 && $times_per_period != "0" && $times_per_period != NULL){
			$everyXMin = 60 / $times_per_period;
		}else{
			$everyXMin = $times_per_period;
		}
	}
}

// Extract information about local apps
$handle = fopen("AppList.txt","r");
$i = 0;
$applist = array();
$tokens = array();
while (($line = fgets($handle)) != false) {
	if(substr($line,0,1) != "#"){
		$tokens = explode(",",$line);
		$applist[$i] = $tokens[0];
		$exelist[$i] = $tokens[1];
		$i++;
	}
}
fclose($handle);

$modifier_tag = "A value that refines the fetch schedule to allow finer control over the recurrence
Valid values are:
       MINUTE: 1 - 60 minutes. (use factors of 60 for good results)
       HOURLY: 1 - 23 hours. (use factors of 24 for good results)";

if($oper_sys == "windows")$modifier_tag .=
"
       DAILY: 1 - 365 days.
       WEEKLY: 1 - 52 weeks.
       MONTHLY: 1 - 12, or FIRST, SECOND, THIRD, FOURTH, LAST, and LASTDAY.";
if($oper_sys == "linux")$modifier_tag .=
"
Days, weeks and months are not supported on Linux servers";

// Write form for fileX and online
if($input_method == "File Exchange"){

	// Get directory structure for FileX
	$res = mysql_query("SELECT name FROM Source WHERE source_id = {$source_id}",$con);
	while ($row = mysql_fetch_array($res))$source_name = $row[0];
	$res = mysql_query("SELECT attribute FROM Dynamic WHERE dynamic_id = {$dynamic_id}",$con);
	while ($row = mysql_fetch_array($res))$dyn_attrib = $row[0];

	// Make table to display to user
	echo ("<form action='AddEditFetcher.php?act=fileX&dynamic_id={$dynamic_id}&source_id={$source_id}' method='post' id='main_form'>");
	echo ("<table><br/>");

}elseif($input_method == "Online"){
	echo ("<form action='AddEditFetcher.php?act=online&dynamic_id={$dynamic_id}&source_id={$source_id}' method='post' id='main_form'>");
	echo ("<table><br/>");
}elseif($MDF_status == "MDF"){
	echo ("<form action='AddEditFetcher.php?act=MDF&dynamic_id={$dynamic_id}&source_id={$source_id}' method='post' id='main_form'>");
	echo ("<table><br/>");
}
echo ("<tr>");
	echo("<td><button type='submit' {$StdRend} > IP address</button></td>");
	echo ("<td>");
	echo("<input type='text' size='25' name='IPAddress' value='{$EG_IP}' />");
	echo ("</td>");
echo ("</tr>");
echo ("<tr>");
	echo("<td><button type='submit' {$StdRend} > User name</button></td>");
	echo ("<td>");
	echo("<input type='text' size='60' name='username' value='{$EG_user}' />");
	echo ("</td>");
echo ("</tr>");
echo ("<tr>");
	echo("<td><button type='submit' {$StdRend} > Password</button></td>");
	echo ("<td>");
	echo("<input type='password' size='60' name='password' value='{$EG_password}' />");
	echo ("</td>");
echo ("</tr>");

echo ("<tr><td>");
echo ("</td></tr>");

echo ("<tr>");
	echo("<td><span title='{$modifier_tag}'><button type='submit' {$StdRend} > Frequency</button></span></td>");
	echo ("<td>");
	echo ("<input type='number' min='1' step='1' size='40' name='Frequent' value='{$everyXMin}'/> &nbsp");
	echo ("<select name='TimeSpan'>");
	echo ("<option value = 'MINUTE'  {$sel_min}>Minute(s)</option>");
	echo ("<option value = 'HOURLY'  {$sel_hr}>Hour(s)</option>");
	if($oper_sys == "windows"){
        echo ("<option value = 'DAILY'   {$sel_day}>Day(s)</option>");
        echo ("<option value = 'WEEKLY'  {$sel_wk}>Week(s)</option>");
        echo ("<option value = 'MONTHLY' {$sel_mnth}>Month(s)</option>");
	}
    echo ("</select>");
	echo ("</td>");
echo ("</tr>");
echo ("<tr>");
	echo("<td><span title='Number of values you expect to receive at this frequency'><button type='submit' {$StdRend} > Items expected</button></span></td>");
	echo ("<td>");
	echo("<input type='number' size='60' min='1' step='1' name='num_items' value='{$num_items_exp}' />");
	echo ("</td>");
echo ("</tr>");
echo ("<tr>");
	echo("<td><span title='Application to convert fetched file to EnTrak input file format'><button type='submit' {$StdRend} > App</button></span></td>");
	echo ("<td>");
	echo ("<select name='AppDestinationLocal' >");
	$i = 0;
	foreach($exelist as $item){
		if(trim($item) == trim($EG_appdestinationLocal))$j = $i;
		$i++;
	}
	$i = 0;
	foreach($applist as $item){
		$selected = "";
		if($i == $j)$selected = "selected";
		echo "<option  {$selected} value=\"{$exelist[$i]}\" name=\"{$exelist[$i]}\">{$item}</option>";
		$i++;
	}
	echo ("</select>");
	echo ("</td>");
echo ("</tr>");
echo ("<tr>");
	echo("<td><span title='Information EnTrak uses to identify which data item to pick in the fetched file'><button type='submit' {$StdRend} >Parameters</button></span></td>");
	echo ("<td>");
	echo("<input type='text' size='60' name='SensorCode' value='{$EG_destination}' placeholder='{$PH}'/>");
	echo ("</td>");
echo ("</tr>");

if($input_method == "File Exchange"){
	echo ("<tr>");
		echo("<td><button type='submit' {$StdRend} > Path</button></td>");
		echo ("<td>");
		echo("<input type='text' size='60' name='FileNameAndPath' value='EnTrak/Inputs/FileX/{$dbase}/{$source_name}_{$source_id}/{$dyn_attrib}_{$dynamic_id}' readonly/>");
		echo ("</td>");
	echo ("</tr>");
}

echo ("</table>");
echo ("<button type='submit' name='UpdateTable' value='OK' >OK</button>&nbsp");
echo ("<button type='submit' name='NotUpdateTable' value='Cancel' >Cancel</button>");




echo "<br/>";
echo ("</form>");
if($GeekMode)echo_advanced_frequency_options("main_form",$start_time_day,$stop_time_day,$day_of_week,$day_of_month,$oper_sys);
if($MDF_status == "MDF" && !$DemoMode){
	echo("<form method='post' action='MDF.php'>");
	echo ("<button type='submit' name='UpdateTable' value='OK' >MDF</button>&nbsp");
	echo("</form>");
}



?>
</body></html>
