//----------------------------------------------------------------------------------
// <copyright file="TelemetryPublisher.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 TelemetryPublisher, a serializable entity class with settings
//   for an originator of telemetry
// </summary>
//
// <owner>Mike Cookson</owner>
//----------------------------------------------------------------------------------

#include "TelemetryPublisher.h"
#include "nsextend.h"
#include <boost/foreach.hpp>
#include <sstream>
#include <stdexcept>

using namespace LiquidRobotics::SMACFramework;
using namespace LiquidRobotics::SMACFramework::XmlDOM;
using namespace std;

namespace LiquidRobotics {
namespace PayloadInterface {

TelemetryPublisher::TelemetryPublisher()
: payloadType(0)
{
}

TelemetryPublisher::TelemetryPublisher(TelemetryPublisherKey _key, PayloadType _payloadType)
: key(_key)
, payloadType(_payloadType)
{
}

int TelemetryPublisher::Compare(FormatCodeToReportParameters::const_iterator it1, FormatCodeToReportParameters::const_iterator it2)
{
	int result;
	const FormatCode fc1 = (*it1).first;
	const FormatCode fc2 = (*it2).first;

	if (fc1 < fc2)
		result = -1;
	else if (fc1 > fc2)
		result = 1;
	else
	{
		TelemetryReportParameters::Ptr rep1 = (*it1).second;
		TelemetryReportParameters::Ptr rep2 = (*it2).second;

		if (*rep1 < *rep2)
			result = -1;
		else if (*rep1 < *rep2)
			result = 1;
		else
			result = 0;
	}

	return result;
}

int TelemetryPublisher::Compare(const TelemetryPublisher& t1, const TelemetryPublisher& t2)
{
	int result = TelemetryPublisherKey::Compare(t1.key, t2.key);

	if (!result)
	{
		if (t1.payloadType < t2.payloadType)
			result = -1;
		else if (t1.payloadType > t2.payloadType)
			result = 1;
	}

	if (!result)
	{
		EventNameToFormatCode::const_iterator it1 = t1.eventNameToFormatCode.begin();;
		EventNameToFormatCode::const_iterator it2 = t2.eventNameToFormatCode.begin();
		bool end1, end2;

		while(end1 = (it1 == t1.eventNameToFormatCode.end()),
			  end2 = (it2 == t2.eventNameToFormatCode.end()),
			  result = (end1 && !end2) ? -1 : ((!end1 && end2) ? 1 : Compare(it1, it2)),
			  !result && !end1)
		{
			++it1;
			++it2;
		}
	}

	if (!result)
	{
		FormatCodeToReportParameters::const_iterator it1 = t1.reportParams.begin();
		FormatCodeToReportParameters::const_iterator it2 = t2.reportParams.begin();
		bool end1, end2;

		while(end1 = (it1 == t1.reportParams.end()),
			  end2 = (it2 == t2.reportParams.end()),
			  result = (end1 && !end2) ? -1 : ((!end1 && end2) ? 1 : Compare(it1, it2)),
			  !result && !end1)
		{
			++it1;
			++it2;
		}
	}

	return result;
}

int TelemetryPublisher::Compare(EventNameToFormatCode::const_iterator it1, EventNameToFormatCode::const_iterator it2)
{
	int result = it1->first.compare(it2->first);

	if (!result)
	{
		if (it1->second < it2->second)
			result = -1;
		else if (it1->second > it2->second)
			result = 1;
		else
			result = 0;
	}

	return result;
}

bool TelemetryPublisher::operator==(const TelemetryPublisher& other) const
{
	return Compare(*this, other) == 0;
}

bool TelemetryPublisher::operator<(const TelemetryPublisher& other) const
{
	return Compare(*this, other) < 0;
}

bool TelemetryPublisher::operator>(const TelemetryPublisher& other) const
{
	return Compare(*this, other) > 0;
}

ostream& TelemetryPublisher::Describe(ostream& stm) const
{
	stm << "key={ " << key << " }"
	    << " payloadType=0x" << ultos(payloadType, 16, 2*sizeof(TelemetryPublisher::PayloadType))
	    << " eventNameToFormatCode={";

	for (EventNameToFormatCode::const_iterator it = eventNameToFormatCode.begin(); it != eventNameToFormatCode.end(); ++it)
	{
		const EventNameToFormatCode::value_type& item = *it;
		stm << "  { eventName='" << item.first << "', formatCode=0x" << ultos(item.second, 16, 2*sizeof(item.second)) << " }";
	}

	stm << " }"
	    <<" reportParams={";

	TelemetryPublisher::FormatCodeArray formatCodes;

	for (FormatCodeToReportParameters::const_iterator it = reportParams.begin(); it != reportParams.end(); ++it)
	{
		const FormatCodeToReportParameters::value_type& item = *it;
		stm << "  { formatCode=0x" << ultos(item.first, 16, 2*sizeof(item.first)) << ", { " << item.second << " } }";
	}

	stm << " }" << endl;
	return stm;
}

void TelemetryPublisher::GetFormatCodes(FormatCodeArray& formatCodes) const
{
	formatCodes.resize(0);

	for (FormatCodeToReportParameters::const_iterator it = reportParams.begin(); it != reportParams.end(); ++it)
		formatCodes.push_back(it->first);
}

TelemetryPublisher::FormatCode TelemetryPublisher::GetFormatCodeForEvent(const string& eventName) const
{
	EventNameToFormatCode::const_iterator it = eventNameToFormatCode.find(eventName);

	if (it == eventNameToFormatCode.end())
	{
		stringstream msg;
		msg << "(TelemetryPublisher::GetFormatCodeForEvent) Publisher " << GetPublisherKey() << " does not publish events from name '" << eventName << "'";
		throw invalid_argument(msg.str());
	}

	return it->second;
}

TelemetryPublisher::PayloadType TelemetryPublisher::GetPayloadType() const
{
	return payloadType;
}

TelemetryPublisherKey TelemetryPublisher::GetPublisherKey() const
{
	return key;
}

TelemetryReportParameters& TelemetryPublisher::GetReportParameters(FormatCode formatCode)
{
	FormatCodeToReportParameters::iterator it = reportParams.find(formatCode);

	if (it == reportParams.end())
	{
		stringstream msg;
		msg << "(TelemetryPublisher::GetReportParameters) Format code " << formatCode << " was not found";
		throw invalid_argument(msg.str());
	}

	return *it->second;
}

const TelemetryReportParameters& TelemetryPublisher::GetReportParameters(FormatCode formatCode) const
{
	return const_cast<TelemetryPublisher*>(this)->GetReportParameters(formatCode);
}

bool TelemetryPublisher::HaveFormatCodeForEvent(const string& eventName) const
{
	EventNameToFormatCode::const_iterator it = eventNameToFormatCode.find(eventName);

	return it != eventNameToFormatCode.end();
}

bool TelemetryPublisher::HaveReportParameters(FormatCode formatCode) const
{
	FormatCodeToReportParameters::const_iterator it = reportParams.find(formatCode);

	return it != reportParams.end();
}

void TelemetryPublisher::SetPayloadType(PayloadType newValue)
{
	payloadType = newValue;
}

void TelemetryPublisher::SetFormatCodeAndEvent(FormatCode formatCode, const string& eventName)
{
	if ((formatCode < 0) || (formatCode > 15))
		throw invalid_argument("Format code must range from 0..15");

	eventNameToFormatCode[eventName] = formatCode;
}

void TelemetryPublisher::SetPublisherKey(TelemetryPublisherKey newValue)
{
	key = newValue;
}

void TelemetryPublisher::SetReportParameters(FormatCode formatCode, const TelemetryReportParameters& newValue)
{
	TelemetryReportParameters::Ptr ptr;
	ptr.reset(new TelemetryReportParameters(newValue));

	reportParams[formatCode] = ptr;
}

void TelemetryPublisher::Load(XmlNode& node, const XmlNVPBase& nvp)
{
	node >> XmlNVP<TelemetryPublisherKey>("key", key);
	node >> XmlNVP<PayloadType>("payloadType", payloadType, XmlNVPBase::defaultAttributeName, XmlNVPBase::HEX);
	node >> XmlNVP<EventNameToFormatCode>("eventNameToFormatCode", eventNameToFormatCode);
	node >> XmlNVP<FormatCodeToReportParameters>("reportParams", reportParams);
}

void TelemetryPublisher::Save(XmlNode& node, const XmlNVPBase& nvp) const
{
	node << XmlNVP<TelemetryPublisherKey>("key", key);
	node << XmlNVP<PayloadType>("payloadType", payloadType, XmlNVPBase::defaultAttributeName, XmlNVPBase::HEX);
	node << XmlNVP<EventNameToFormatCode>("eventNameToFormatCode", eventNameToFormatCode);
	node << XmlNVP<FormatCodeToReportParameters>("reportParams", reportParams);;
}

ostream& operator<<(ostream& stm, const TelemetryPublisher& pub)
{
	return pub.Describe(stm);
}

}
}
