//------------------------------------------------------------------------------
// <copyright file="MD5-2.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>
// </summary>
//
// <owner></owner>
//------------------------------------------------------------------------------

#include "MD5-2.h"
#include "md5.h"
#include "DoThrow.h"
#include <exception>
#include <sstream>
#include <boost/foreach.hpp>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "LqrSMACException.h"
#include "LqrSMACPrintfBuffer.h"
#include "nsextend.h"

using namespace std;
using namespace boost;
using namespace LiquidRobotics::SMACFramework;

namespace LiquidRobotics {
namespace PayloadInterface {

IMPLEMENT_INNER_EXCEPTION(MD5, FileNotFound, std::runtime_error)
IMPLEMENT_INNER_EXCEPTION(MD5, FileIOError, std::runtime_error)

MD5::MD5()
: pContext(NULL)
{
}

MD5::~MD5()
{
	if (pContext)
		delete (MD5_CTX*) pContext;
}

void MD5::AllocateContext()
{
	if (!pContext)
	{
		pContext = new MD5_CTX;
		MD5Init((MD5_CTX*) pContext);
	}
}

void MD5::Append(const void* pData, int sequenceLength)
{
	AllocateContext();
	MD5Update((MD5_CTX*) pContext, (unsigned char*) pData, (unsigned int) sequenceLength);
}

void MD5::AppendFileContent(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 << "MD5::AppendFileContent could not open '"
		    << fileName
		    << "' for read: error="
		    << errnoSave
		    << " ("
		    << strerror(errnoSave)
		    << ")";

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

	ArrayType buffer;
	buffer.resize(512);

	int status;

	do
	{
		do
		{
			status = read(fd, &buffer.at(0), buffer.size());
			errnoSave = errno;
		} while((status == -1) && (errnoSave == EINTR));

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

			stringstream stm;

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

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

		else if (status)
			Append(&buffer.at(0), status);

	} while(((ArrayType::size_type) status) == buffer.size());

	close(fd);
}

MD5::Entity MD5::Final(bool resetContext)
{
	AllocateContext();

	MD5_CTX* pCon = (MD5_CTX*) pContext;
	MD5Final(pCon);

	ArrayType a(pCon->digest, sizeof(pCon->digest));

	if (resetContext)	Reset();
	return Entity(a);
}

void MD5::Reset()
{
	AllocateContext();
	::MD5Init((MD5_CTX*) pContext);
}

const unsigned MD5::Entity::MD5_Size = 16;

MD5::Entity::Entity()
: bytes(MD5_Size, 0)
{
}

MD5::Entity::Entity(const ArrayType& data)
: bytes(data)
{
	CheckArrayParam("data", "MD5::Entity::Entity", data);
}

MD5::Entity::Entity(const byte* pData)
{
	bytes.assign(pData, MD5_Size);
}

MD5::Entity::Entity(const Entity& right)
: bytes(right.bytes)
{
}

MD5::Entity::~Entity()
{
}

MD5::Entity& MD5::Entity::operator=(const Entity& right)
{
	if (this != &right)
		bytes = right.bytes;

	return *this;
}

bool MD5::Entity::operator==(const Entity& right) const
{
	return bytes == right.bytes;
}

bool MD5::Entity::operator!=(const Entity& right) const
{
	return !operator==(right);
}

const MD5::ArrayType& MD5::Entity::GetBytes() const
{
	return bytes;
}

void MD5::Entity::SetBytes(const ArrayType& newValue)
{
	CheckArrayParam("newSValue", "MD5::Entity::SetBytes", newValue);

	bytes = newValue;
}

void MD5::Entity::CheckArrayParam(const char* paramName, const char* caller, const ArrayType& data)
{
	if (data.size() != MD5_Size)
	{
		stringstream sstm;
		sstm << caller << ": " << paramName << " parameter size should be " << MD5_Size << ", not " << data.size();

		throw InvalidArgument(paramName, sstm.str().c_str());
	}
}

SHARED_LIB_PUBLIC ostream& operator<<(ostream& out, const MD5::Entity& right)
{
	const MD5::ArrayType& data = right.GetBytes();

	BOOST_FOREACH(MD5::ArrayType::value_type i, data)
		out << ultos(i, 16, 2);

	return out;
}

}
}
