//------------------------------------------------------------------------------
// <copyright file="AsynchronousCommandInvoker.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>
// 	Definitions for AsynchronousCommandInvoker, which allows for execution of
//  commands and asynchronous responses.
// </summary>
//
// <owner>Mike Cookson</owner>
//------------------------------------------------------------------------------

#include "EventTransceiver.h"
#include "LqrSMACDeclareException.h"
#include "LqrSMACIObjectBroker.h"
#include "LqrSMACSharedLib.h"
#include "LqrSMACSemaphore.h"
#include <map>
#include <stdexcept>
#include <string>
#include <typeinfo>
#include <boost/shared_ptr.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/recursive_mutex.hpp>

namespace LiquidRobotics {
namespace EventLib {

class SHARED_LIB_PUBLIC AsynchronousCommandInvoker : public boost::noncopyable
{
public:

	typedef CORBA::Any Any;
	typedef CORBA::Any_var Any_var;
	typedef LiquidRobotics::EventLib::EventTransceiver EventTransceiver;
	typedef CORBA::Exception CORBAException;
	typedef std::exception exception;
	typedef LiquidRobotics::SMAC::ICommandable ICommandable;
	typedef LiquidRobotics::SMAC::ICommandable_var ICommandable_var;
	typedef LiquidRobotics::SMACFramework::IObjectBroker IObjectBroker;
	typedef boost::unique_lock<AsynchronousCommandInvoker> Lock;
	typedef boost::shared_ptr<AsynchronousCommandInvoker> Ptr;
	typedef LiquidRobotics::SMACFramework::Semaphore Semaphore;
	typedef std::string string;
	typedef std::type_info type_info;

	DECLARE_EXCEPTION(Shutdown, std::runtime_error);
	DECLARE_EXCEPTION(Timeout, std::runtime_error);

	// Clients instantiate this object for each invocation in order to synchronously or asynchronously wait
	// for completions and handle it as the Ptr subtype
	class InvokeWaitObject
	{
	public:

		typedef std::list<Any_var> ResultList;
		typedef boost::shared_ptr<InvokeWaitObject> Ptr;
		typedef boost::signals2::signal<void (InvokeWaitObject& sender, const Any& result, const type_info* errPtr,
				const string& errTypeName, const string& errDetail, bool lastEvent)> CompletionSignalType;
		typedef boost::signals2::scoped_connection ScopedConnection;
		typedef boost::shared_ptr<ScopedConnection> ScopedConnectionPtr;

		InvokeWaitObject();
		virtual ~InvokeWaitObject();

		virtual const ResultList& AwaitCompletion(float numSeconds = -1.0f);
		virtual void Complete(Any_var result, bool lastReport = true);
		virtual void CompleteWithError(CORBAException& corbaEx);
		virtual void CompleteWithError(exception& ex);
		virtual const string& GetTransactionID() const;
		virtual void ResetWaitable(const string& transID);

		CompletionSignalType CompletionSignal;

	private:

		typedef boost::recursive_mutex Mutex;
		typedef boost::unique_lock<Mutex> Lock;

		Mutex mutex;
		Semaphore sem;
		string transID;
		const type_info* errPtr;
		string errTypeName;
		string errDetail;
		ResultList resultList;
		bool active;
	};

	// Clients can use this derived class to store additional data to identify the event
	template<typename TParam, typename TStored = TParam> class InvokeWaitObjectT : public InvokeWaitObject
	{
	public:

		InvokeWaitObjectT(TParam _userData) : userData(_userData) { }

		TStored userData;
	};

	AsynchronousCommandInvoker(IObjectBroker& _broker, EventTransceiver& _eventTrans, const string& _requester, const string& _transPrefix);

	void Initialize();
	void Invoke(const string& command, const string& targetName, const string& targetKind, InvokeWaitObject::Ptr waitObject);
	void Invoke(const CORBA::Any& command, const string& targetName, const string& targetKind, InvokeWaitObject::Ptr waitObject);
	void Invoke(const string& command, ICommandable_var target, InvokeWaitObject::Ptr waitObject);
	void Invoke(const CORBA::Any& command, ICommandable_var target, InvokeWaitObject::Ptr waitObject);
	void InvokeIOR(const string& command, const string& targetIOR, InvokeWaitObject::Ptr waitObject);
	void InvokeIOR(const CORBA::Any& command, const string& targetIOR, InvokeWaitObject::Ptr waitObject);

	// Lockable concept methods that enables a Lock to
	// lock and unlock the instance
	virtual void lock();
	virtual bool try_lock();
	virtual void unlock();

private:

	typedef std::map<string,InvokeWaitObject::Ptr> TransIDToWaitMap;
	typedef boost::recursive_mutex Mutex;

	ICommandable_var GetCommandable(const string& targetName, const string& targetKind);
	ICommandable_var GetCommandableFromIOR(const string& targetIOR);
	string NextTransID();
	void UnlinkTransID(const string& transID);

	Mutex mutex;
	IObjectBroker& broker;
	EventTransceiver& eventTrans;
	const string requester;
	string prefix;
	long nextID;
	TransIDToWaitMap transIDToWaitMap;
};

}
}
