//------------------------------------------------------------------------------
// <copyright file="LqrSMACByteStream.h" 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>
//	Declarations for ByteStream and its support classes; ByteStream is used to
//	read or write consecutively-stored bytes in a byte array.
// </summary>
//
// <owner>Mike Cookson</owner>
//------------------------------------------------------------------------------

#ifndef __LQRSMACBYTESTREAM_H__
#define __LQRSMACBYTESTREAM_H__

#include <stdint.h>
#include <sstream>
#include <stdexcept>
#include <string>
#include "LqrSMACBitConvert.h"
#include "LqrSMACByteArray.h"
#include "LqrSMACDeclareException.h"
#include "LqrSMACSharedLib.h"

namespace LiquidRobotics {
namespace SMACFramework {

class SHARED_LIB_PUBLIC ByteStream
{
public:

	typedef BitConvert::Endianness Endianness;
	typedef std::string string;

	DECLARE_EXCEPTION(CompleteWithBytesRemaining, std::runtime_error);
	DECLARE_EXCEPTION(InvalidByteCountForStreamedType, std::runtime_error);
	DECLARE_EXCEPTION(NotValidOnInputStream, std::logic_error);
	DECLARE_EXCEPTION(NotValidOnOutputStream, std::logic_error);
	DECLARE_EXCEPTION(StreamUnderflow, std::runtime_error);

	ByteStream();																						// output stream (native format)
	ByteStream(Endianness _endian);																		// output stream
	ByteStream(const ByteArray& ba, size_t startOffset = 0, size_t reservedAtEnd = 0);						// input stream (native format)
	ByteStream(Endianness _endian, const ByteArray& ba, size_t startOffset = 0, size_t reservedAtEnd = 0);	// input stream
	virtual ~ByteStream();

	const ByteArray& AsBytes() const;									// returns the current stream as bytes (temporary reference)
	Endianness GetEndian() const { return endian; }

	// -- input stream --
	size_t CountRemaining() const;
	ByteArray::byte Get();												// throws if nothing left to get

	template<typename T>
	void GetRaw(T& t)
	{
		ByteArray::byte* pData = (ByteArray::byte*) &t;
		size_t countLeft = sizeof(t);

		while(countLeft--)
			*pData++ = Get();
	}

	const ByteArray& GetRemaining(size_t reservedAtEnd = 0);			// returns a temporary reference
	void VerifyExhausted() const;										// throws if there are any bytes remaining
	void VerifyExhausted(const string& typeName) const;					// throws if there are any bytes remaining and mentions the type being serialized

	// -- output stream --
	void Put(ByteArray::byte data);										// appends a byte to the end
	void Put(const ByteArray& data);									// appends a byte array to the end

	template<typename T>
	void PutRaw(const T& t)
	{
		const ByteArray::byte* pData = (const ByteArray::byte*) &t;
		size_t countLeft = sizeof(t);

		while(countLeft--)
			Put(*pData++);
	}

private:

	typedef std::stringstream stringstream;

	const Endianness endian;
	const ByteArray* const baPtr;
	size_t baOffset;
	size_t baReserved;
	stringstream ss;
	ByteArray remaining;
	ByteArray streamAsBytes;
};

class SHARED_LIB_PUBLIC IByteStreamableIn
{
public:

	virtual ~IByteStreamableIn() { }

	virtual ByteStream& StreamIn(ByteStream& inStream) = 0;
};

class SHARED_LIB_PUBLIC IByteStreamableOut
{
public:

	virtual ~IByteStreamableOut() { }

	virtual ByteStream& StreamOut(ByteStream& outStream) const = 0;
};

class SHARED_LIB_PUBLIC IByteStreamable : public IByteStreamableIn, public IByteStreamableOut
{
public:

	virtual ~IByteStreamable() { }
};

template<typename StreamedType>
class SHARED_LIB_PUBLIC ContainerIn : public IByteStreamableIn
{
public:

	ContainerIn(StreamedType& _stype)
	: stype(_stype)
	, specifiesLength(false)
	, numElements(0)
	{
	}

	ContainerIn(StreamedType& _stype, size_t _numElements)
	: stype(_stype)
	, specifiesLength(true)
	, numElements(_numElements)
	{
	}

	virtual ByteStream& StreamIn(ByteStream& inStream)
	{
		size_t numEle = numElements;

		if (!specifiesLength)
		{
			const size_t bytesLeft = inStream.CountRemaining();

			if (bytesLeft % sizeof(typename StreamedType::value_type))
				throw ByteStream::InvalidByteCountForStreamedType("The number of bytes left does not fit evenly into streamed type");

			numEle = bytesLeft/sizeof(typename StreamedType::value_type);
		}

		size_t idx = 0;

		stype.resize(numEle);

		while(numEle--)
			inStream >> stype[idx++];

		return inStream;
	}

	StreamedType& stype;
	const bool specifiesLength;
	const size_t numElements;
};

template<typename StreamedType>
class SHARED_LIB_PUBLIC ContainerOut : public IByteStreamableOut
{
public:

	ContainerOut(const StreamedType& _stype)
	: stype(_stype)
	{
	}

	virtual ByteStream& StreamOut(ByteStream& outStream) const
	{
		size_t numEle = stype.size();
		size_t idx = 0;

		while(numEle--)
			outStream << stype[idx++];

		return outStream;
	}

	const StreamedType& stype;
};

template<typename SizeType, typename StreamedType>
class SHARED_LIB_PUBLIC CountedContainerIn : public IByteStreamableIn
{
public:

	CountedContainerIn(StreamedType& _stype)
	: stype(_stype)
	{
	}

	virtual ByteStream& StreamIn(ByteStream& inStream)
	{
		SizeType containerCount = 0;
		size_t idx = 0;

		inStream >> containerCount;

		stype.resize(containerCount);

		while(containerCount--)
			inStream >> stype[idx++];

		return inStream;
	}

private:

	StreamedType& stype;
};

template<typename SizeType, typename StreamedType>
class SHARED_LIB_PUBLIC CountedContainerOut : public IByteStreamableOut
{
public:

	CountedContainerOut(StreamedType& _stype)
	: stype(_stype)
	{
	}

	virtual ByteStream& StreamOut(ByteStream& outStream) const
	{
		SizeType containerCount = stype.size();;
		size_t idx = 0;

		outStream << containerCount;

		while(containerCount--)
			outStream << stype[idx++];

		return outStream;
	}

private:

	const StreamedType& stype;
};

ByteStream& operator<<(ByteStream& stm, const char& data);
ByteStream& operator<<(ByteStream& stm, const int8_t& data);
ByteStream& operator<<(ByteStream& stm, const uint8_t& data);
ByteStream& operator<<(ByteStream& stm, const int16_t& data);
ByteStream& operator<<(ByteStream& stm, const uint16_t& data);
ByteStream& operator<<(ByteStream& stm, const int32_t& data);
ByteStream& operator<<(ByteStream& stm, const uint32_t& data);
ByteStream& operator<<(ByteStream& stm, const int64_t& data);
ByteStream& operator<<(ByteStream& stm, const uint64_t& data);
ByteStream& operator<<(ByteStream& stm, const float& data);
ByteStream& operator<<(ByteStream& stm, const double& data);
inline ByteStream& operator<<(ByteStream& stm, const IByteStreamableOut& data) { return data.StreamOut(stm); }

ByteStream& operator>>(ByteStream& stm, char& data);
ByteStream& operator>>(ByteStream& stm, int8_t& data);
ByteStream& operator>>(ByteStream& stm, uint8_t& data);
ByteStream& operator>>(ByteStream& stm, int16_t& data);
ByteStream& operator>>(ByteStream& stm, uint16_t& data);
ByteStream& operator>>(ByteStream& stm, int32_t& data);
ByteStream& operator>>(ByteStream& stm, uint32_t& data);
ByteStream& operator>>(ByteStream& stm, int64_t& data);
ByteStream& operator>>(ByteStream& stm, uint64_t& data);
ByteStream& operator>>(ByteStream& stm, float& data);
ByteStream& operator>>(ByteStream& stm, double& data);
inline ByteStream& operator>>(ByteStream& stm, IByteStreamableIn& data) { return data.StreamIn(stm); }

}
}

#endif
