//------------------------------------------------------------------------------
// <copyright file="LqrSMACByteStream.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 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>
//------------------------------------------------------------------------------

#include "LqrSMACByteStream.h"

using namespace std;

namespace LiquidRobotics {
namespace SMACFramework {

IMPLEMENT_INNER_EXCEPTION(ByteStream, CompleteWithBytesRemaining, runtime_error);
IMPLEMENT_INNER_EXCEPTION(ByteStream, InvalidByteCountForStreamedType, runtime_error);
IMPLEMENT_INNER_EXCEPTION(ByteStream, NotValidOnInputStream, logic_error);
IMPLEMENT_INNER_EXCEPTION(ByteStream, NotValidOnOutputStream, logic_error);
IMPLEMENT_INNER_EXCEPTION(ByteStream, StreamUnderflow, runtime_error);

ByteStream::ByteStream()
: endian(BitConvert::NATIVE_END)
, baPtr(NULL)
, baOffset(0)
, baReserved(0)
{

}

ByteStream::ByteStream(Endianness _endian)
: endian(_endian)
, baPtr(NULL)
, baOffset(0)
, baReserved(0)
{
}

ByteStream::ByteStream(const ByteArray& ba, size_t startOffset, size_t reservedAtEnd)
: endian(BitConvert::NATIVE_END)
, baPtr(&ba)
, baOffset(startOffset)
, baReserved(reservedAtEnd)
{
}

ByteStream::ByteStream(Endianness _endian, const ByteArray& ba, size_t startOffset, size_t reservedAtEnd)
: endian(_endian)
, baPtr(&ba)
, baOffset(startOffset)
, baReserved(reservedAtEnd)
{
}

ByteStream::~ByteStream()
{
}

const ByteArray& ByteStream::AsBytes() const
{
	if (baPtr)
		const_cast<ByteArray&>(streamAsBytes).assign(baPtr->begin(), baPtr->end());
	else
	{
		string temp = ss.str();
		const ByteArray::byte* pStart = (const ByteArray::byte*) temp.data();

		const_cast<ByteArray&>(streamAsBytes).assign(pStart, pStart+temp.length());
	}

	return streamAsBytes;
}

size_t ByteStream::CountRemaining() const
{
	if (!baPtr)
		throw NotValidOnOutputStream("CountRemaining operation is not valid on an output stream");

	size_t countRemaining = 0;

	if (baPtr->size() > (baOffset+baReserved))
		countRemaining = baPtr->size()-(baOffset+baReserved);

	return countRemaining;
}
ByteArray::byte ByteStream::Get()
{
	if (!baPtr)
		throw NotValidOnOutputStream("Get operation is not valid on an output stream");

	ByteArray::byte result = 0;

	if (baPtr->size() > (baOffset+baReserved))
		result = baPtr->at(baOffset++);
	else
		throw StreamUnderflow("No more bytes available in stream for Get");

	return result;
}

const ByteArray& ByteStream::GetRemaining(size_t reservedAtEnd)
{
	if (!baPtr)
		throw NotValidOnOutputStream("GetRemaining operation is not valid on an output stream");
	else if (baPtr->size() <= (baOffset+baReserved+reservedAtEnd))
		throw StreamUnderflow("Not enough bytes available in stream for GetRemaining");
	else
	{
		ByteArray::const_iterator ciStart = baPtr->begin()+baOffset;
		ByteArray::const_iterator ciEnd = baPtr->end()-(baReserved+reservedAtEnd);

		baOffset += (ciEnd-ciStart);
		remaining.assign(ciStart, ciEnd);
		return remaining;
	}
}

void ByteStream::VerifyExhausted() const
{
	if (!baPtr)
		throw NotValidOnOutputStream("VerifyExhausted operation is not valid on an output stream");

	else if (baPtr->size() > (baOffset+baReserved))
	{
		stringstream msg;
		msg << "Stream input completed with " << (baPtr->size()-(baOffset+baReserved)) << " extra bytes remaining";
		throw CompleteWithBytesRemaining(msg.str());
	}
}

void ByteStream::VerifyExhausted(const string& typeName) const
{
	if (!baPtr)
		throw NotValidOnOutputStream("VerifyExhausted operation is not valid on an output stream");

	else if (baPtr->size() > (baOffset+baReserved))
	{
		stringstream msg;
		msg << "Stream input completed for type " << typeName << " with " << (baPtr->size()-(baOffset+baReserved)) << " extra bytes remaining";
		throw CompleteWithBytesRemaining(msg.str());
	}
}

void ByteStream::Put(ByteArray::byte data)
{
	if (baPtr)
		throw NotValidOnOutputStream("Put operation is not valid on an input stream");

	ss << data;
}

void ByteStream::Put(const ByteArray& data)
{
	if (baPtr)
		throw NotValidOnOutputStream("Put operation is not valid on an input stream");

	if (data.size())
		ss.write((const char*) &data.front(), data.size());
}

ByteStream& operator<<(ByteStream& stm, const char& data)			{ const ByteArray::byte d = (ByteArray::byte) data; stm.Put(d); return stm; }
ByteStream& operator<<(ByteStream& stm, const int8_t& data)			{ const ByteArray::byte d = (ByteArray::byte) data; stm.Put(d); return stm; }
ByteStream& operator<<(ByteStream& stm, const uint8_t& data)		{ const ByteArray::byte d = (ByteArray::byte) data; stm.Put(d); return stm; }
ByteStream& operator<<(ByteStream& stm, const int16_t& data)		{ const int16_t temp = data; BitConvert::ReverseNumeric(temp, stm.GetEndian()); stm.PutRaw(temp); return stm; }
ByteStream& operator<<(ByteStream& stm, const uint16_t& data)		{ const uint16_t temp = data; BitConvert::ReverseNumeric(temp, stm.GetEndian()); stm.PutRaw(temp); return stm; }
ByteStream& operator<<(ByteStream& stm, const int32_t& data)		{ const int32_t temp = data; BitConvert::ReverseNumeric(temp, stm.GetEndian()); stm.PutRaw(temp); return stm; }
ByteStream& operator<<(ByteStream& stm, const uint32_t& data)		{ const uint32_t temp = data; BitConvert::ReverseNumeric(temp, stm.GetEndian()); stm.PutRaw(temp); return stm; }
ByteStream& operator<<(ByteStream& stm, const int64_t& data)		{ const int64_t temp = data; BitConvert::ReverseNumeric(temp, stm.GetEndian()); stm.PutRaw(temp); return stm; }
ByteStream& operator<<(ByteStream& stm, const uint64_t& data)		{ const uint64_t temp = data; BitConvert::ReverseNumeric(temp, stm.GetEndian()); stm.PutRaw(temp); return stm; }
ByteStream& operator<<(ByteStream& stm, const float& data)			{ stm.PutRaw(data); return stm; }
ByteStream& operator<<(ByteStream& stm, const double& data)			{ stm.PutRaw(data); return stm; }
//ByteStream& operator<<(ByteStream& stm, const IByteStreamableOut& data) { return data.StreamOut(stm); }

ByteStream& operator>>(ByteStream& stm, char& data)					{ stm.GetRaw((ByteArray::byte&) data); return stm; }
ByteStream& operator>>(ByteStream& stm, int8_t& data)				{ stm.GetRaw((ByteArray::byte&) data); return stm; }
ByteStream& operator>>(ByteStream& stm, uint8_t& data)				{ stm.GetRaw((ByteArray::byte&) data); return stm; }
ByteStream& operator>>(ByteStream& stm, int16_t& data)				{ stm.GetRaw(data); BitConvert::ReverseNumeric(data, stm.GetEndian()); return stm; }
ByteStream& operator>>(ByteStream& stm, uint16_t& data)				{ stm.GetRaw(data); BitConvert::ReverseNumeric(data, stm.GetEndian()); return stm; }
ByteStream& operator>>(ByteStream& stm, int32_t& data)				{ stm.GetRaw(data); BitConvert::ReverseNumeric(data, stm.GetEndian()); return stm; }
ByteStream& operator>>(ByteStream& stm, uint32_t& data)				{ stm.GetRaw(data); BitConvert::ReverseNumeric(data, stm.GetEndian()); return stm; }
ByteStream& operator>>(ByteStream& stm, int64_t& data)				{ stm.GetRaw(data); BitConvert::ReverseNumeric(data, stm.GetEndian()); return stm; }
ByteStream& operator>>(ByteStream& stm, uint64_t& data)				{ stm.GetRaw(data); BitConvert::ReverseNumeric(data, stm.GetEndian()); return stm; }
ByteStream& operator>>(ByteStream& stm, float& data)				{ stm.GetRaw(data); return stm; }
ByteStream& operator>>(ByteStream& stm, double& data)				{ stm.GetRaw(data); return stm; }
//ByteStream& operator>>(ByteStream& stm, IByteStreamableIn& data) 	{ return data.StreamIn(stm); }

}
}
