<?php
/*
    Copyright (C) 2016 - 2017 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/>.
*/

namespace GnuBoat;

require_once(__DIR__ ."/../autoloader.php");

class ServiceData extends Service
{
	function __construct()
	{
		parent::__construct();
		// configure roundings per value (key) and precision (value)
		$this->_configRound = array
		(
			"latitude" => 4,
			"longitude" => 4,
			"speedthroughwater" => 1,
			"speedoverground" => 1,
			"courseoverground" => 1,
			"waterdepth" => 1,
			"watertemperature" => 1,
		);
	}

	protected function process()
	{
		$debug = $this->debug();
		$config = new Config();
		$dbFile = $config->databaseFile();

		$result = array();
		$result["lastvalid"] = array();
		$result["track"] = array();

		if(!file_exists($dbFile))
			return $this->error("Database file ". $dbFile ." does not exist");

		// Fetch entries of the last 30s with maximum (available) resolution of 2s
		$this->addRrdData($dbFile, "2", "240", $result, $lastValid);
		if($lastValid !== false){
			$result["lastvalid"] = $lastValid->toArray();
		}
		// Fetch entries of the last 1h with maximum (available) resolution of 10s
		$this->addRrdData($dbFile, "10", "36000", $result, $lastTime);
		// Fetch entries of the last 24h with maximum (available) resolution of 60s
		$this->addRrdData($dbFile, "60", "86400", $result, $lastTime);

		return $this->output($result);
	}

	private function addRrdData($dbFile, $interval, $period, &$result, &$lastValid){
		$debug = $this->debug();
		$lastValid = false;

		$endTime = floor(time() / $interval) * $interval;
		$startTime = $endTime - $period;
		$data = rrd_fetch($dbFile, array("AVERAGE", "--resolution", $interval, "--start", $startTime, "--end", $endTime));
		// $data = rrd_fetch($dbFile, array("AVERAGE", "--resolution", $interval, "--start", "-". $period, "--end", "start+". $period, "--align-start"));
		if($data === false)
			return $this->error("Failure reading rrd database ". $dbFile .": ". rrd_error(), $result); 

		if($debug > 2){
			var_dump($data);
		}

		$data = $data["data"];

		// transform them into json format
		$i = 0;
		$lastValid = false;
		$keys = array_keys($data);
		$keyTimeframes = $keys[0];
		$itemCount = count($keys);
		if($itemCount < 0 )
			return $this->error("No keys in fetched rrd data from ". $dbFile);

		$timeframesCount = count($data[$keyTimeframes]);
		if($debug > 1){
			error_log("Variables: ". $itemCount ."; Timeframes: ". $timeframesCount);
		}
		foreach($data[$keys[0]] as $timeframe => $value){
			$tmp = new TrackItem($timeframe);
			foreach($keys as $key){
				$value = $data[$key][$timeframe];
				if(array_key_exists($key, $this->_configRound) && is_integer($this->_configRound[$key]))
					$value = round($value, $this->_configRound[$key]);
				if(!$tmp->setProperty($key, $value) && $debug > 1)
					error_log("Coult not set property ". $key ." to value ". $value ." at ". $timeframe);
			}
			// only add the timeframe to the track, if the values are valid and we had a gps fix at that time
			if($tmp->isValid()){
				$lastValid = $tmp;
				if($tmp->gpsFixed()){
					if(!array_key_exists($timeframe, $result["track"])){
						$result["track"][$timeframe] = $tmp->toArray();
					}
				}
			}
			else{
				if($debug > 1){
					echo "Failed <pre>";
					var_dump($tmp);
					echo "</pre>\n";
				}
			}
		}
		ksort($result["track"]);
	}
}
?>
