//------------------------------------------------------------------------------
// <copyright file="VirtualRelayProgram.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>
// 	Declaration of VirtualRelayProgram class
// </summary>
//
// <owner>Arash Ushani</owner>
//------------------------------------------------------------------------------

#ifndef __VirtualRelayProgram_H__
#define __VirtualRelayProgram_H__

#include "VirtualRelayController.h"
#include "EventTransceiver.h"
#include "FCCMessageEvent.h"
#include "ChannelStateEvent.h"
#include "ChannelRequestEvent.h"
#include "LqrSMACIdl.h"
#include "LqrSMACSharedLib.h"
#include "LqrSMACTimerCollection.h"
#include "PayloadManagerClient.h"
#include <boost/shared_ptr.hpp>
#include <boost/signals2.hpp>
#include <boost/asio.hpp>
#include <stdint.h>

// Config file for the VirtualRelayProgram settings
#define VIRTUAL_RELAY_CONFIG_FILE	"VirtualRelay-config.xml"

#define MAJOR	1
#define MINOR	2
#define BUILD	2150

namespace LiquidRobotics {

namespace EventLib {
	class IEventBase;
}

namespace SMACFramework {
	class IObjectBroker;
	class Logger;
	class PayloadDescription;
}

namespace VirtualRelay {

class VirtualRelayProgramSettings;
class VirtualRelayController;

class SHARED_LIB_PUBLIC VirtualRelayProgram
: public LiquidRobotics::EventLib::EventTransceiver
, public LiquidRobotics::SMACFramework::ICommandableBase
{
public:

	typedef LiquidRobotics::SMACFramework::IObjectBroker IObjectBroker;
	typedef LiquidRobotics::EventLib::IEventBase IEventBase;
	typedef LiquidRobotics::EventLib::FCCMessageEvent FCCMessageEvent;
	typedef LiquidRobotics::EventLib::ChannelStateEvent ChannelStateEvent;
	typedef LiquidRobotics::EventLib::ChannelRequestEvent RequestEvent;
	typedef LiquidRobotics::SMACFramework::Logger Logger;
	typedef LiquidRobotics::EventLib::PayloadManagerClient PayloadManagerClient;
	typedef LiquidRobotics::SMACFramework::PayloadDescription Desc;
	typedef boost::signals2::scoped_connection ScopedConnection;
	typedef boost::shared_ptr<ScopedConnection> ScopedConnectionPtr;
	typedef LiquidRobotics::SMACFramework::TimerCollection<void*> TimerCollection;
	typedef boost::shared_ptr<VirtualRelayController> ControllerPtr;
	typedef std::map<int, ControllerPtr> ControllerMap;
	typedef EventLib::EventPropertyValue::UInt8Vector UInt8Vector;
	typedef boost::signals2::mutex Mutex;
	typedef unsigned char byte;

	static const std::string CMD_SET_SLEEP_TIME;
	static const std::string CMD_SET_RETRY_RATE;
	static const std::string CMD_SET_NUM_RETRIES;
	static const std::string CMD_SET_TELEMETRY_INTERRUPT;
	static const std::string CMD_SET_ACK_INTERRUPT;
	static const std::string CMD_SET_TIMEOUT;

	VirtualRelayProgram(IObjectBroker& _broker, VirtualRelayProgramSettings& _settings, Logger& _logger);
	virtual ~VirtualRelayProgram();

	virtual void Initialize(Object_ptr _pServer, PayloadManagerClient::Ptr _pmClient);

	// IPingable operations
    virtual ::CORBA::Double Ping();

    // IPayloadDevice
    virtual ::LiquidRobotics::SMAC::EnumerationData* GetEnumerationData();
    virtual void PowerOff(::LiquidRobotics::SMAC::PowerOffTimeType offDelay);
    virtual void PowerOn();
    virtual ::LiquidRobotics::SMAC::BoardIDType boardID();
    virtual ::LiquidRobotics::SMAC::PayloadDescription* description();
    virtual ::LiquidRobotics::SMAC::EPayloadEnableState enableState();
    virtual ::LiquidRobotics::SMAC::PowerOffTimeType requestOffTime();
    virtual ::LiquidRobotics::SMAC::PowerOnTimeType requestOnTime();
    virtual ::LiquidRobotics::SMAC::ComponentVersion* softwareVersion();
    virtual ::LiquidRobotics::SMAC::TaskIDType taskID();

    // ICommandable
    virtual void SendCommand(const ::CORBA::Any& command, const char* requester, const char* transactionID, ::CORBA::Any_OUT_arg result);

private:

	void SubscribeToEvents();

	void GetVehicleUniqueID();

	string ProcessCommand(const string& command);

	// Controller Signal Handling
	void HandleIncomingMessageFromShore(const VirtualRelayController& sender, const UInt8Vector& incomingMessage);
	void HandleChannelRequests(const VirtualRelayController& sender, bool state);
	void HandleTelemetryTimeout(VirtualRelayController& sender);

	// Fire Events
	void FireIncomingCommand(const UInt8Vector& command, int address);
	void FireMessageViaIridium(const UInt8Vector& message);
	void FireChannelRequestEvent(bool state, int protocolRevision);

	// Stock FCC Messages
	void ReadVehicleUniqueID();
	void SetDefaultCommsToIridium();

	// Event Handling
	void FCCOutgoingMessageEventHandler(EventTransceiver& sender, const IEventBase& receivedEvent);
	void FCCOutgoingMessageEventHandler_Asynch(const FCCMessageEvent& receivedEvent);
	void ChannelStateHandler(EventTransceiver& sender, const IEventBase& receivedEvent);
	void ShutdownHandler(EventTransceiver& sender, const IEventBase& receivedEvent);

	bool receivedUniqueID;

	IObjectBroker& broker;
	VirtualRelayProgramSettings& settings;
	Logger& logger;
	TimerCollection timerCollection;
	PayloadManagerClient::Ptr pmClient;

	ControllerMap controllers;

	ScopedConnectionPtr connectionToShutdownEvent;
	ScopedConnectionPtr connectionToFCCIncomingMessageEvent;
	ScopedConnectionPtr connectionToChannelStateEvent;

	std::vector<ScopedConnectionPtr> controllerIncomingMessageConnections; // these messages come from shore
	std::vector<ScopedConnectionPtr> controllerChannelRequestConnections;
	std::vector<ScopedConnectionPtr> controllerTelemetryTimeoutConnections;
};

}
}

#endif
