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

class Nmea0183Sentence extends \GnuBoat\Nmea\NmeaSentence
{
	function __construct($type, $talker, $checksum, $sentence)
	{
		parent::__construct($type, $talker, $sentence);
	
		$this->_checksum = strtolower($checksum);
	}
	
	public function checksum()
	{
		return $this->_checksum;
	}
	
	public function checksumValid(&$errorMessage)
	{
		// extract characters to calculate checksum
		$matches = array();
		$result = preg_match('/^[\$!]{1}([^\*]+)\*([\da-zA-Z]+)$/', $this->sentence(), $matches);
		if($result === false || $result == 0 || count($matches) != 3){
			$errorMessage .= "Unable to determine ascii content and checksum from ". $this->sentence() ."\n";
			return false;
		}
		
		$sentenceChecksum = strtolower($matches[2]);
		if($this->checksum() != $sentenceChecksum){
			$errorMessage .= "Checksum from sentece (". $sentenceChecksum .") is not equal stored checksum (". $this->checksum() .")\n";
			return false;
		}
		
		// calculate checksum
		$checksum = 0;
		for($i = 0; $i < strlen($matches[1]); $i++)
			$checksum = $checksum ^ ord($matches[1][$i]);

		if($sentenceChecksum == strtolower(dechex($checksum)))
			return true;
		$errorMessage .= "Checksum from sentence (". $sentenceChecksum .") is not equal calculated checksum (". dechex($checksum) .")\n";
		return false;
	}
	
	/**
	 * @brief Abstract function to provide additional checks in your implementation.
	 *
	 * Called by valid() and must return true or false
	 */
	protected function validate(&$errorMessage)
	{
		return $this->checksumValid($errorMessage);
	}
	
	private $_checksum;
}

?>
