//-----------------------------------------------------------------------------------
// <copyright file="TelemetryBuffer.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 TelemetryBuffer, a collection of telemetry reports and settings
//   in progress.
// </summary>
//
// <owner>Mike Cookson</owner>
//-----------------------------------------------------------------------------------

#ifndef __PAYLOADINTERFACELIB_TELEMETRYBUFFER_H__
#define __PAYLOADINTERFACELIB_TELEMETRYBUFFER_H__

#include "IEventBase.h"
#include "LqrSMACSemaphore.h"
#include "LqrSMACSharedLib.h"
#include "LqrSMACSignalSubscriber.h"
#include "LqrSMACXmlDOM.h"
#include "TelemetryFieldLibrary.h"
#include "TelemetryPublisher.h"
#include "TelemetryPublisherKey.h"
#include "TelemetryReport.h"
#include "TelemetryReportKey.h"
#include <map>
#include <ostream>
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/signals2.hpp>

#include "LqrSMACLogger.h"


namespace LiquidRobotics {
namespace EventLib {
	class IEventBase;
	class PayloadManagerClient;
	class TelemetrySettingsChangedEvent;
}
}

namespace LiquidRobotics {
namespace SMACFramework {
	class ByteArray;
	class IObjectBroker;
}
}

namespace LiquidRobotics {
namespace PayloadInterface {

class SHARED_LIB_PUBLIC TelemetryBuffer
{
public:

	typedef PayloadMessage::BoardAddress BoardAddress;
	typedef LiquidRobotics::SMACFramework::ByteArray ByteArray;
	typedef LiquidRobotics::SMACFramework::XmlDOM::IXmlDOMPersistent IXmlDOMPersistent;
	typedef TelemetryReportKey::FormatCode FormatCode;
	typedef LiquidRobotics::EventLib::IEventBase IEventBase;
	typedef LiquidRobotics::SMACFramework::IObjectBroker IObjectBroker;
	typedef std::map<TelemetryPublisherKey, TelemetryPublisher::Ptr> KeyToPublisher;
	typedef std::ostream ostream;
	typedef LiquidRobotics::EventLib::PayloadManagerClient PayloadManagerClient;
	typedef boost::shared_ptr<TelemetryBuffer> Ptr;
	typedef boost::signals2::scoped_connection ScopedConnection;
	typedef boost::shared_ptr<ScopedConnection> ScopedConnectionPtr;
	typedef LiquidRobotics::EventLib::TelemetrySettingsChangedEvent TelemetrySettingsChangedEvent;
	typedef std::string string;
	typedef LiquidRobotics::SMACFramework::XmlDOM::XmlNode XmlNode;
	typedef LiquidRobotics::SMACFramework::XmlDOM::XmlNVPBase XmlNVPBase;
	typedef LiquidRobotics::SMACFramework::Logger Logger;

	class SHARED_LIB_PUBLIC Config : public IXmlDOMPersistent
	{
	public:

		typedef boost::shared_ptr<Config> Ptr;

		Config(IObjectBroker& _broker, PayloadManagerClient& _pmclient);
		Config(const Config& other);

		Config& operator=(const Config& other);
		bool operator==(const Config& other) const;

		const TelemetryFieldLibrary& GetFieldLibrary() const;
		void SetFieldLibrary(const TelemetryFieldLibrary& newValue);

		KeyToPublisher& GetPublishers();
		const KeyToPublisher& GetPublishers() const;
		void SetPublishers(const KeyToPublisher& newValue);

		void Load(const string& fileName);
		void Save(const string& fileName) const;

		void Load(XmlNode& node, const XmlNVPBase& nvp);
		void Save(XmlNode& node, const XmlNVPBase& nvp) const;

	private:

		friend class boost::serialization::access;

		void UpdateBoardID();

		template<class Archive>
		void load(Archive& ar, const unsigned int version)
		{
			ar >> BOOST_SERIALIZATION_NVP(publishers);
			UpdateBoardID();
			fieldLibrary.Load(ar);
		}

		template<class Archive>
		void save(Archive& ar, const unsigned int version) const
		{
			ar << BOOST_SERIALIZATION_NVP(publishers);
			fieldLibrary.Save(ar);
		}

		BOOST_SERIALIZATION_SPLIT_MEMBER()

		void DeepCopy(const Config& other);

		IObjectBroker& broker;
		PayloadManagerClient& pmclient;
		KeyToPublisher publishers;
		TelemetryFieldLibrary fieldLibrary;
	};


	TelemetryBuffer(IObjectBroker& _broker, PayloadManagerClient& _pmclient);
	TelemetryBuffer(IObjectBroker& _broker, const Config& config);
	TelemetryBuffer(const TelemetryBuffer& other);

	TelemetryBuffer& operator=(const TelemetryBuffer& other);

	virtual void ClearPending(TelemetryPublisherKey publisher);
	virtual void ClearPending(TelemetryPublisherKey publisher, TelemetryPublisher::FormatCode formatCode);
	virtual ostream& DescribeState(ostream& stm) const;
	virtual const Config& GetConfig() const;
	virtual void InitializeAutoPublishWaitingTelemetry(Logger& logger);
	virtual void ProcessEvent(const IEventBase& evt);
	virtual void ProcessTelemetryChangedEvent(const TelemetrySettingsChangedEvent& evt);
	virtual void PublishPending(TelemetryPublisherKey publisher);
	virtual void PublishPending(TelemetryPublisherKey publisher, TelemetryPublisher::FormatCode formatCode);
	virtual void PublishTimedOut (Logger& logger);
	virtual void SavePosition(double newLat, double newLon);
	virtual void SetMaxRetainTime(TelemetryPublisherKey publisher, FormatCode formatCode, time_t newValue);
	virtual void SetMaxSamples(TelemetryPublisherKey publisher, FormatCode formatCode, uint16_t newValue);

	typedef boost::signals2::signal<void (TelemetryBuffer& sender, TelemetryReportKey reportKey, BoardAddress targetAddress, const ByteArray& content)> TelemetryReportSignalType;
private:
	typedef LiquidRobotics::SMACFramework::LockableConceptMutex LockableConceptMutex;
	LockableConceptMutex firingMutex;
	TelemetryReportSignalType telemetryReportSignal;
public:
	LiquidRobotics::SMACFramework::SignalSubscriber<TelemetryReportSignalType> telemetryReportSubscriber;

private:

	struct EventItem
	{
		EventItem()
		{
		}

		/*EventItem(const TelemetryReportKey& _reportKey, BoardAddress _targetAddress, const ByteArray& _content)
		: reportKey(_reportKey)
		, targetAddress(_targetAddress)
		, content(_content.begin(), _content.end())
		{
		}*/

		TelemetryReportKey reportKey;
		BoardAddress targetAddress;
		ByteArray::Ptr contentp;
	};

	typedef boost::shared_ptr<EventItem> EventItemPtr;
	typedef std::list<EventItemPtr> EventItemPtrList;
	typedef std::map<TelemetryReportKey, TelemetryReport::Ptr> KeyToReport;
	typedef LiquidRobotics::SMACFramework::Semaphore Semaphore;
	typedef boost::shared_ptr<boost::thread> ThreadPtr;

	unsigned ComputeNextTimeout() const;
	static void DeepCopy(KeyToReport& destination, const KeyToReport& source);
	void Format(IEventBase& evt, const TelemetryPublisher& pub, const TelemetryFieldList& fieldList, uint16_t bytesToFollow, ByteArray& seq);
	EventItemPtr FormatEventItem(TelemetryReportKey rptKey, TelemetryReport& report);
	bool GetEventInfo(const IEventBase& evt, TelemetryPublisherKey& pubKey, TelemetryPublisher::Ptr& pub, bool formatCodeCase = false) const;
	void Publish(EventItemPtr eventp);
	void Publish(EventItemPtrList& events);
	void Publish(TelemetryReportKey rptKey, TelemetryReport& report);
	void TimeoutThread(Logger* loggerp);

	LockableConceptMutex localMutex;			// local mutex to protect structures
	IObjectBroker& broker;						// object broker used for CORBA interactions
	Config config;								// configuration of the buffer
	KeyToReport keyToReport;					// dynamic buffering of reports
	double savedLatitude;						// latitude from external source
	double savedLongitude;						// longitude from external source
	Semaphore timeoutWakeup;					// a semaphore that wakes up the timeout thread
	ThreadPtr timeoutThread;					// a thread that publishes telemetry that has timed out

	//static const IEventBase::PropertyNameType boardIDTag;			// board ID supplied by original event
	static const IEventBase::PropertyNameType formatCodeTag;		// format code supplied by configuration (not valid in original event)
	static const IEventBase::PropertyNameType lengthToFollowTag;	// length of data to follow in packet (not valid in original event)
	static const IEventBase::PropertyNameType numSamplesTag;		// number of samples (after adding current tag, not valid in original event)
	static const IEventBase::PropertyNameType payloadTypeTag;		// payload type supplied by original event
	//static const IEventBase::PropertyNameType taskIDTag;			// task ID supplied by configuration or in original event
};

SHARED_LIB_PUBLIC std::ostream& operator<<(std::ostream& stm, const TelemetryBuffer::Config& settings);

}
}

#endif
