//----------------------------------------------------------------------------------
// <copyright file="SensorController.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/implementation of SensorController template class, which acts
//	 as the base implementation of the service controller object.  The purpose of the
//   controller is to orchestrate the various widgets to implement the service, with
//	 the exception of the CORBA interface.  The controller might be reused unchanged
//	 if CORBA were removed.  It includes responsibilities for executing commands and
//	 firing out status changes with boost events.
//
//	 The template parameters are:
//
//		- TSCCmdBase, the controller interface that is made available to all commands,
//		  usually abstract; this will be a base class for SensorController
//
//		- TCmdBase, the abstract base class that defines command operations
//
//		- TCmdID, the type if command ID that is used to track commands
//
//		- TExceptions, a class-based namespaces for exceptions that can be thrown
// </summary>
//
// <owner>Mike Cookson</owner>
//----------------------------------------------------------------------------------

#ifndef __EventLib_SensorController_h__
#define __EventLib_SensorController_h__

#include "GPSSampleEvent.h"
#include "LqrSMACCmdLineParser.h"
#include "LqrSMACCmdOutputFormatter.h"
#include "LqrSMACCmdOutputFormatterCF.h"
#include "LqrSMACLogger.h"
#include "LqrSMACQueueWorker.h"
#include "LqrSMACSharedLib.h"
#include "LqrSMACSignalSubscriber.h"
#include "SendCommandCompleteEvent.h"
#include "SensorControllerBaseCmdID.h"
#include "SensorControllerMultipleLinesCmd.h"
#include <sstream>
#include <stdexcept>
#include <vector>
#include <boost/signals2.hpp>
#include <boost/utility.hpp>

namespace LiquidRobotics {

namespace SMACFramework {
	class IObjectBroker;
}

namespace EventLib  {

template<class TSCCmdBase, class TCmdBase, class TCmdID, class TExceptions>
class SHARED_LIB_PUBLIC SensorController
: public TSCCmdBase
, public boost::noncopyable
{
public:

	typedef TSCCmdBase TCon;
	typedef TCmdBase TCmd;
	typedef TCmdID TCID;
	typedef TExceptions TEx;
	typedef SensorController<TSCCmdBase,TCmdBase,TCmdID, TExceptions> SensorControllerT;
	typedef std::string string;
	typedef LiquidRobotics::SMACFramework::CmdOutputFormatter CmdOutputFormatter;
	typedef LiquidRobotics::SMACFramework::CmdOutputFormatterCF CmdOutputFormatterCF;
	typedef boost::signals2::signal<void (const TCmdID& cmdID, const string& result)> CommandCompleteSignalType;
	typedef boost::signals2::signal<void (const TCmdID& cmdID, const string& result, bool success)> CommandCompleteSignal2Type;
	typedef boost::signals2::signal<void (const GPSSampleEvent& sample)> GPSSampleEventSignalType;
	typedef boost::signals2::signal<void ()> ShutdownSignalType;
	typedef LiquidRobotics::SMACFramework::IObjectBroker IObjectBroker;
	typedef LiquidRobotics::SMACFramework::Logger Logger;
	typedef boost::signals2::scoped_connection ScopedConnection;
	typedef boost::shared_ptr<ScopedConnection> ScopedConnectionPtr;
	typedef LiquidRobotics::SMACFramework::SignalSubscriber<GPSSampleEventSignalType> GPSSignalSubscriber;
	typedef LiquidRobotics::SMACFramework::SignalSubscriber<ShutdownSignalType> ShutdownSignalSubscriber;

	SensorController(IObjectBroker& _broker, Logger& _logger, GPSSignalSubscriber::Ptr _gpsSubscriber, ShutdownSignalSubscriber::Ptr _shutdownSubscriber)
	: broker(_broker)
	, logger(_logger)
	, initialized(false)
	, gpsSubscriber(_gpsSubscriber)
	, shutdownSubscriber(_shutdownSubscriber)
	{
	}

	virtual ~SensorController()
	{
	}

	virtual void Initialize()
	{
		using namespace std;

		MutexLock lock(mutex);

		if (initialized)
		{
			stringstream msg;
			msg << "Unexpected call to " << typeid(*this).name() << "::Initialize when already initialized";

			throw runtime_error(msg.str());
		}

		try
		{
			if (gpsSubscriber)
				gpsConnection = gpsSubscriber->Subscribe(boost::bind(&SensorControllerT::OnGPSSampleEvent, this, _1));

			if (shutdownSubscriber)
				shutdownConnection = shutdownSubscriber->Subscribe(boost::bind(&SensorControllerT::OnShutdownEvent, this));

			commandQueue.reset(new CommandQueue(0));
			cqHandleWorkItemConnection = commandQueue->SubscribeWorkItemProcessed(boost::bind(&SensorControllerT::OnProcessCommand, this, _1, _2));
			commandQueue->Initialize();
			initialized = true;
		}
		catch(...)
		{
			cqHandleWorkItemConnection.reset();
			commandQueue.reset();
			shutdownSubscriber.reset();
			gpsSubscriber.reset();
			throw;
		}
	}

	virtual bool Initialized() const
	{
		return initialized;
	}

	virtual void Shutdown()
	{
		MutexLock lock(mutex);

		if (initialized)
		{
			initialized = false;
			try { cqHandleWorkItemConnection.reset(); }		catch (...) { }
			try { shutdownSubscriber.reset(); }				catch (...) { }
			try { gpsSubscriber.reset(); }					catch (...) { }
			CommandQueuePtr tempCQ = commandQueue;
			try { commandQueue.reset(); }					catch (...) { }
			lock.unlock();
			if (tempCQ)
				tempCQ->Shutdown();
		}
	}

	virtual string SendCommand(typename TSCCmdBase::ParsingContext& context)
	{
		using namespace std;
		string result;

		__Msg __msg(logger);
		const TCmdID& cmdID = context.GetID();
		__msg.head << "SendCommand command='" << context.GetCmd() << "' requester='" << cmdID.GetRequester() << "' transactionID='" << cmdID.GetTransactionID() << "'";
		__msg.PrintFront();

		MutexLock lock(mutex);

		if (!initialized)
		{
			__msg.tail << "NotReady(Not initialized)";
			stringstream msg;
			msg << "Not initialized (" << typeid(*this).name() << ")";
			throw typename TExceptions::NotReady(msg.str());
		}

		lock.unlock();

		try
		{
			typename TSCCmdBase::CommandPtr cmdp = ParseCommandBuffer(context);

			CmdOutputFormatter::Ptr fmt = cmdOutputFormatterCF.Create(GetDefaultOutputFormatter());
			fmt->SetCommandName(context.GetCmd());
			cmdp->SetOutputFormatter(fmt);

			if (EnqueueCommand(cmdp))
			{
				cmdp->ActionWait(result);
				__msg.tail << "'" << result << "'";
			}
			else
				throw typename TExceptions::ReturnsAsynchronously("Command will return asynchronously");
		}
		catch(exception& ex)
		{
			__msg.tail << "Caught " << typeid(ex).name() << "(" << ex.what() << ")";
			throw;
		}

		return result;
	}

	virtual ScopedConnectionPtr SubscribeCommandComplete(typename CommandCompleteSignalType::slot_type slot)
	{
		ScopedConnectionPtr result;
		result.reset(new ScopedConnection(commandCompleteSignal.connect(slot)));
		return result;
	}

	virtual ScopedConnectionPtr SubscribeCommandComplete2(typename CommandCompleteSignal2Type::slot_type slot)
	{
		ScopedConnectionPtr result;
		result.reset(new ScopedConnection(commandCompleteSignal2.connect(slot)));
		return result;
	}

	virtual string GetDefaultOutputFormatter() const
	{
		return "xml";
	}

protected:

	typedef typename TSCCmdBase::CommandPtr CommandPtr;
	typedef LiquidRobotics::SMACFramework::QueueWorker<CommandPtr> CommandQueue;
	typedef boost::shared_ptr<CommandQueue> CommandQueuePtr;
	typedef boost::recursive_mutex Mutex;
	typedef boost::unique_lock<Mutex> MutexLock;

	struct __Msg
	{
		__Msg(Logger& _logger) : logger(_logger) 	{ }
		~__Msg()									{ PrintTail(); }

		void PrintFront()
		{
			using namespace std;
			Logger::Locked(logger)->Info << "Entering " << head.str() << endl;
		}

		void PrintTail()
		{
			using namespace std;
			Logger::Locked(logger)->Info << "Exiting " << head.str() << ": " << tail.str() << endl;
		}

		Logger& logger;
		std::stringstream head;
		std::stringstream tail;
	};

	virtual bool EnqueueCommand(typename TSCCmdBase::CommandPtr cmdp, bool awaitCompletion = false)
	{
		if (!awaitCompletion)
			awaitCompletion = cmdp->IsBlocking();

		commandQueue->EnqueueWorkItem(cmdp);

		if (awaitCompletion || cmdp->IsBlocking())
		{
			string dummy;
			cmdp->ActionWait(dummy);
			return true;
		}
		else
			return false;
	}

	virtual typename TSCCmdBase::CommandPtr ParseCommandBuffer(typename TSCCmdBase::ParsingContext& context)
	{
		using namespace std;
		using namespace boost;

		vector<string> commandLines;
		string trimmedCommand = context.GetCmd();
		trim(trimmedCommand);
		split(commandLines, trimmedCommand, is_any_of("\r\n"), token_compress_on);

		typename TSCCmdBase::CommandPtr cmdp;

		if (commandLines.size() == 1)
			cmdp = ParseCommand(context);
		else
			cmdp = SensorControllerMultipleLinesCmd<TSCCmdBase,TCmdBase,TCmdID,TExceptions>::Parse(*this, commandLines, context, logger);

		cmdp->SetCompletionParams(context.GetID());
		return cmdp;
	}

	virtual typename TSCCmdBase::CommandPtr ParseCommand(typename TSCCmdBase::ParsingContext& context, bool internalCmd = false)
	{
		using namespace std;
		using namespace LiquidRobotics::SMACFramework;

		CmdLineParser parser(context.GetCmd());
		typename TSCCmdBase::CommandPtr result;

		if (result)
			;

		else
		{
			stringstream msg;
			msg << typeid(*this).name() << "::Parse: unrecognized command: " << context.GetCmd();

			throw invalid_argument(msg.str());
		}

		return result;
	}

	virtual bool TryInitialize()
	{
		bool result = false;

		using namespace std;

		if (initialized)
		{
			stringstream msg;
			msg << "Unexpected call to " << typeid(*this).name() << "::Initialize when already initialized";

			throw runtime_error(msg.str());
		}

		try
		{
			if (gpsSubscriber)
				gpsConnection = gpsSubscriber->Subscribe(boost::bind(&SensorControllerT::OnGPSSampleEvent, this, _1));

			if (shutdownSubscriber)
				shutdownConnection = shutdownSubscriber->Subscribe(boost::bind(&SensorControllerT::OnShutdownEvent, this));

			result = true;
		}
		catch(...)
		{
			shutdownSubscriber.reset();
			gpsSubscriber.reset();
		}

		return result;
	}

	virtual void OnGPSSampleEvent(const GPSSampleEvent& sample)
	{
	}

	virtual void OnProcessCommand(CommandQueue& sender, const typename TSCCmdBase::CommandPtr& cmdp)
	{
		using namespace std;

		__Msg __msg(logger);
		__msg.head << "OnProcessCommand " << typeid(*cmdp).name();
		__msg.PrintFront();

		bool caughtException = false;
		string result;

		try
		{
			cmdp->Execute();
		}
		catch(exception& ex)
		{
			__msg.tail << "Caught " << typeid(ex).name() << " (" << ex.what() << ")";
			result = __msg.tail.str();
			caughtException = true;
		}
		catch(...)
		{
			__msg.tail << "Caught unknown exception";
			result = __msg.tail.str();
			caughtException = true;
		}

		cmdp->SignalComplete();

		if (!cmdp->IsBlocking())
		{
			if (!caughtException)
			{
				try
				{
					cmdp->ActionWait(result);
					__msg.tail << "'" << result << "'";
				}
				catch(exception& ex)
				{
					__msg.tail << "Caught " << typeid(ex).name() << " (" << ex.what() << ")";
					if (cmdp && !cmdp->GetOutputFormatter()) result = __msg.tail.str();
					caughtException = true;
				}
				catch(...)
				{
					__msg.tail << "Caught unknown exception";
					if (cmdp && !cmdp->GetOutputFormatter()) result = __msg.tail.str();
					caughtException = true;
				}

				const TCmdID& cmdID = cmdp->GetCompletionParams();

				commandCompleteSignal(cmdID, result);
				commandCompleteSignal2(cmdID, result, !caughtException && cmdp->GetSuccessFlag());
			}
		}

		if (cmdp && !cmdp->GetOutputFormatter() && !result.length())
			result = "Success";

		if (!caughtException && !__msg.tail.tellp())
			__msg.tail << result;
	}

	virtual void OnShutdownEvent()
	{
		Shutdown();
	}

	Mutex mutex;
	IObjectBroker& broker;
	Logger& logger;
	bool initialized;
	CmdOutputFormatterCF cmdOutputFormatterCF;
	CommandCompleteSignalType commandCompleteSignal;
	CommandCompleteSignal2Type commandCompleteSignal2;
	GPSSignalSubscriber::Ptr gpsSubscriber;
	ShutdownSignalSubscriber::Ptr shutdownSubscriber;
	ScopedConnectionPtr gpsConnection;
	ScopedConnectionPtr shutdownConnection;
	CommandQueuePtr commandQueue;
	ScopedConnectionPtr cqHandleWorkItemConnection;
};

}
}

#endif
