<?php
/*
    Copyright (C) 2016 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

require_once(__DIR__ ."/inc/Config.php");
$config = new Config();
$dbFile = $config->databaseFile();

define("REQUEST_DATA", "data");
define("REQUEST_SHUTDOWN", "shutdown");


// configure roundings per value (key) and precision (value)
$configRound = array
(
	"latitude" => 5,
	"longitude" => 5,
	"speedthroughwater" => 1,
	"speedoverground" => 1,
	"waterdepth" => 1,
	"watertemperature" => 1,
);

function addRrdData($interval, $period, &$result, &$lastTime){
	global $dbFile;
	global $debug;
	global $configRound;

	$data = rrd_fetch($dbFile, array( "AVERAGE", "--resolution", $interval, "--start", "-". $period, "--end", "start+". $period));
	if($data === false){
		echo json_encode($result);
		$message = "Failure reading rrd database ". $dbFile .": ". rrd_error(); 
		if($debug > 0)
			echo $message;
		else
			error_log($message);
	}

	if($debug > 2){
		echo "<pre>";
		var_dump($data);
		echo "</pre>";
	}

	$data = $data["data"];

	// transform them into json format
	$i = 0;
	$lastTime = -1;
	$keys = array_keys($data);
	if(count($keys) < 0 ){
		error_log("No keys in fetched rrd data from ". $dbFile);
		echo json_encode("");
		exit;
	}
	if($debug > 0){
		echo "<p>Variables: ". count($keys) ."; Timeframes: ". count($data[$keys[0]]) ."</p>\n";
	}
	for($i = 0; $i < count($data[$keys[0]]); $i++){
		$time = array_keys($data[$keys[0]])[$i];
		$allValid = true;
		$tmp = array();
		foreach($keys as $key){
			if($key == "gpsfix"){
				switch($data[$key][$time]){
					case 1:
						$tmp[$key] = "2D";
						break;
					case 2:
						$tmp[$key] = "3D";
						break;
					default:
						$tmp[$key] = "-";
				}
			}
			else{
				$tmp[$key] = $data[$key][$time];
				if(!is_numeric($tmp[$key]) || is_nan($tmp[$key])){
					$allValid = false;
					if($debug > 1){
						echo "Invalid value ". $key ." (". $tmp[$key] .") at time ". $time ."<br/>";
					}
				}
				elseif(array_key_exists($key, $configRound) && is_integer($configRound[$key]))
					$tmp[$key] = round($tmp[$key], $configRound[$key]);
			}
		}
		// only add the timeframe to the track, if the values are valid and we had a gps fix at that time
		if($allValid){
 			if(!array_key_exists($time, $result["track"])){
				$result["track"][$time] = $tmp;
 			}
			$lastTime = $time;
		}
		else{
			if($debug > 1){
				echo "Failed <pre>";
				var_dump($tmp);
				echo "</pre>\n";
			}
		}
	}

 	ksort($result["track"]);
}

$debug = 0;
if(array_key_exists("debug", $_GET))
	$debug = $_GET["debug"];

$request = REQUEST_DATA;
if(array_key_exists("request", $_GET)){
	$request = $_GET["request"];
}

if($debug == 0)
	header('Content-Type: application/json');

$result = array();
if($request == REQUEST_SHUTDOWN){
	$handle = @fopen("/var/spool/gnuboat/shutdown.request", "w");
	if($handle === false){
		$message = "Could not create file to indicate shutdown to the daemon (Timezone: ". date_default_timezone_get() .")";
		if($debug > 0)
			echo $message;
		error_log($message);
		$result["shutdownstart"] = -1;
	}
	else{
		$shutdownTime = new DateTime('NOW');
		$shutdownTime->modify("+15 seconds");
		fwrite($handle, $shutdownTime->format(DateTime::ISO8601));
		$result["shutdownstart"] = $shutdownTime->format(DateTime::ISO8601);
	}
}
elseif($request == REQUEST_DATA){
	$result["lastvalid"] = array();
	$result["track"] = array();

	if(!file_exists($dbFile)){
		echo json_encode("");
		if($debug > 0)
			echo "Database file ". $dbFile ." does not exist!";
		error_log("Database file ". $dbFile ." does not exist");
		exit;
	}
	// Fetch entries of the last 30 seconds
	addRrdData("5s", "30s", $result, $lastTime);
	if($lastTime > -1){
		$result["lastvalid"] = $result["track"][$lastTime];
	}
 	addRrdData("15s", "5minutes", $result, $lastTime);
 	addRrdData("30s", "12h", $result, $lastTime);
}

if($debug > 0){
	echo json_encode($result,  JSON_PRETTY_PRINT);
}
else{
	echo json_encode($result);
}

?>
