//------------------------------------------------------------------------------
// <copyright file="CRC16.cpp" company="LiquidRobotics">
//
// Copyright (c) 2014 Liquid Robotics, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// This software is associated with a release.  Liquid Robotics makes no
// representation that the design, interfaces or component distribution will
// remain unchanged in future releases.
//
// </copyright>
//
// <summary>
//   Implementation of the CRC16 class, which generates and holds the value of a
//   16-bit CRC (cyclic redundancy check)
// </summary>
//
// <owner>Mike Cookson</owner>
//------------------------------------------------------------------------------

#include "CRC16.h"
#include "DoThrow.h"
#include "LqrSMACPrintfBuffer.h"
#include "nsextend.h"
#include <stdexcept>
#include <sstream>
#include <boost/foreach.hpp>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;
using namespace LiquidRobotics::SMACFramework;

namespace LiquidRobotics {
namespace PayloadInterface {

const CRC16::CRCType CRC16::defaultInitialValue = 0;

IMPLEMENT_INNER_EXCEPTION(CRC16, FileNotFound, std::runtime_error);
IMPLEMENT_INNER_EXCEPTION(CRC16, FileIOError, std::runtime_error);


CRC16::CRC16(const void* pData, unsigned dataLength, CRCType initial)
: crc(initial)
{
	Add(pData, dataLength);
}

inline CRC16::CRCType UpdateCRC(CRC16::CRCType crc, CRC16::byte data)
{
	crc ^= data;

	for (int i = 0; i < 8; ++i)
	{
		if (crc & 1)
			crc = (crc >> 1) ^ 0xA001;
		else
			crc = (crc >> 1);
	}

	return crc;
}

void CRC16::Add(byte b)
{
	crc = UpdateCRC(crc, b);
}

void CRC16::Add(const void* pData, unsigned dataLength)
{
	if (!pData) DoThrow<invalid_argument>(__FILE__, __LINE__, "pData is NULL");

	const byte* pByte = (const byte*) pData;

	while(dataLength--)
		crc = UpdateCRC(crc, *pByte++);
}

void CRC16::Add(const ByteArray& data)
{
	BOOST_FOREACH(byte b, data)
		crc = UpdateCRC(crc, b);
}

string CRC16::ToString() const
{
	stringstream stm;

	stm << *this;
	return stm.str();
}

void CRC16::AddFileContent(const string& fileName)
{
	int fd;
	int errnoSave;

	do
	{
		fd = open(fileName.c_str(), O_RDONLY);
		errnoSave = errno;
	} while((fd == -1) && (errnoSave == EINTR));

	if (fd == -1)
	{
		stringstream stm;

		stm << "CRC16::AddFileContent could not open '"
		    << fileName
		    << "' for read: error="
		    << errnoSave
		    << " ("
		    << strerror(errnoSave)
		    << ")";

		string msg = stm.str();
		DoThrow<FileNotFound>(__FILE__, __LINE__, msg);
	}

	byte buffer[512];
	int status;

	do
	{
		do
		{
			status = read(fd, buffer, sizeof(buffer));
			errnoSave = errno;
		} while((status == -1) && (errnoSave == EINTR));

		if (status == -1)
		{
			close(fd);

			stringstream stm;

			stm << "CRC16::AddFileContent could not read '"
			    << fileName
			    << "': error="
			    << errnoSave
			    << " ("
			    << strerror(errnoSave)
			    << ")";

			string msg = stm.str();
			DoThrow<FileIOError>(__FILE__, __LINE__, msg);
		}

		else if (status)
			Add(buffer, status);

	} while(status == sizeof(buffer));

	close(fd);
}

ostream& operator<<(ostream& out, const CRC16& crc)
{
	out << "0x" << ultos(crc.Get(), 16, 4);
	return out;
}


}
}
