<?php
/*
    Copyright (C) 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 ServiceReplay extends Service
{
	function __construct()
	{
		parent::__construct();
	}

	protected function process()
	{
		$debug = $this->debug();
		$config = new Config();
		if($debug > 1)
			print "Log directory: ". $config->logDirectory() ."\n";

		if(!array_key_exists("logfile", $_POST)){
			return $this->error("No logfile to replay selected");
		}

		// prepare a download of available log files
		$file = $config->logDirectory() . $_POST["logfile"];
		if(!file_exists($file))
			return $this->error("Logfile ". $file ." not found");
		
		$parser = new Nmea\Parser();
		$nmeaSentences = $parser->parseFile($file, '0183');
		if($nmeaSentences == null)
			return error("Error parsing logfile ". $file);
		
		$result = ["track" => []];
		$currentItem = new TrackItem();
		foreach($nmeaSentences as $sentence){
			if($sentence->type() == "rmc"){
				if($currentItem->isValid()){
					$result["track"][$currentItem->timestamp()] = $currentItem->toArray();
					$currentItem = new TrackItem();
				}
				$currentItem->setDateTime($sentence->dateTime());
				$currentItem->setLatitude($sentence->latitude());
				$currentItem->setLongitude($sentence->longitude());
				$currentItem->setSpeedOverGround($sentence->speedOverGround());
				$currentItem->setCourseOverGround($sentence->courseOverGround());
			}
			elseif($sentence->type() == "dpt"){
				$currentItem->setWaterDepth($sentence->depth());
			}
			elseif($sentence->type() == "mtw"){
				$currentItem->setWaterTemperature($sentence->temperature());
			}
		}
		if($currentItem->isValid())
			$result["track"][$currentItem->timestamp()] = $currentItem->toArray();

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

?>
