<?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\Nmea;

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

/**
 * @brief Use this class to parse a single NMEA sentence (parseSentence()) or a complete file (parseFile())
 *
 */
class Parser
{
	function __construct($debug = 0)
	{
		$this->_debug = $debug;
	
		$this->_formats = array();
		if(canClassBeLoaded("GnuBoat\Nmea\Nmea0183\Parser"))
			$this->_formats["0183"] = "GnuBoat\Nmea\Nmea0183\Parser";
	}
	
	public function formatsSupported()
	{
		return array_keys($this->_formats);
	}
	
	/**
	 * @brief Returns an array of NmeaSentence objects, specialized for the type of sentence
	 */
	function parseFile($file, $format)
	{
		return call_user_func(array(new $this->_formats[$format], "parseFile"), $file, $this->_debug);
	}
	
	/**
	 * @brief Returns an NmeaSentence object, specialized for the type of sentence
	 */
	function parseSentence($sentence, $format)
	{
		if(!array_key_exists($format, $this->_formats)){
			$message = "No handler for requested format ". $format ." found\n";
			error_log($message);
			if($this->_debug > 0)
				print $message;
			return null;
		}
		
		if(empty($sentence)){
			$message = "Empty sentence\n";
			error_log($message);
			if($this->_debug > 0)
				print $message;
			return null;
		}
		
		return call_user_func(array(new $this->_formats[$format], "parseSentence"), $sentence, $this->_debug);
	}

	private $_formats;
	private $_debug;
}

?>
