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

#include "AsynchronousCommandInvoker.h"
#include <sstream>
#include <LqrSMACIdl.h>
#include "LqrSMACIObjectBroker-inline.h"
#include "LqrSMACUptime.h"
#include "nsextend.h"

using namespace std;
//using namespace LiquidRobotics::EventLib;
using namespace LiquidRobotics::SMAC;
using namespace LiquidRobotics::SMACFramework;

namespace LiquidRobotics {
namespace EventLib {

IMPLEMENT_INNER_EXCEPTION(AsynchronousCommandInvoker,Shutdown,std::runtime_error);
IMPLEMENT_INNER_EXCEPTION(AsynchronousCommandInvoker,Timeout,std::runtime_error);

AsynchronousCommandInvoker::AsynchronousCommandInvoker(IObjectBroker& _broker, EventTransceiver& _eventTrans, const string& _requester, const string& _transPrefix)
: broker(_broker)
, eventTrans(_eventTrans)
, requester(_requester)
, nextID(1)
{
	stringstream pfx;
	pfx << _transPrefix << ":" << ltos((long) this, 16) << ":";

	prefix = pfx.str();
}

void AsynchronousCommandInvoker::Initialize()
{
}

void AsynchronousCommandInvoker::Invoke(const string& command, const string& targetName, const string& targetKind, InvokeWaitObject::Ptr waitObject)
{
	Invoke(command, GetCommandable(targetName, targetKind), waitObject);
}

void AsynchronousCommandInvoker::Invoke(const CORBA::Any& command, const string& targetName, const string& targetKind, InvokeWaitObject::Ptr waitObject)
{
	Invoke(command, GetCommandable(targetName, targetKind), waitObject);
}

void AsynchronousCommandInvoker::Invoke(const string& command, ICommandable_var target, InvokeWaitObject::Ptr waitObject)
{
	Any a;
	a <<= command.c_str();
	Invoke(a, target, waitObject);
}

void AsynchronousCommandInvoker::Invoke(const CORBA::Any& command, const ICommandable_var target, InvokeWaitObject::Ptr waitObject)
{
	Lock lock(*this);

	if (!waitObject)
		waitObject.reset(new InvokeWaitObject());

	const string nextTransID = NextTransID();

	waitObject->ResetWaitable(nextTransID);
	transIDToWaitMap[nextTransID] = waitObject;

	lock.unlock();

	try
	{
		Any_var result;
		ICommandableInvoker<ICommandable_var> invoker(const_cast<ICommandable_var&>(target));
		invoker(command, requester.c_str(), nextTransID.c_str(), result);

		UnlinkTransID(nextTransID);
		waitObject->Complete(result);
	}
	catch(LiquidRobotics::SMAC::WillCompleteAsynchronously&)
	{
		// background event handler will post completion
	}
	catch(CORBAException& corbaEx)
	{
		UnlinkTransID(nextTransID);
		if (lock) lock.unlock();
		waitObject->CompleteWithError(corbaEx);
	}
	catch(exception& ex)
	{
		UnlinkTransID(nextTransID);
		if (lock) lock.unlock();
		waitObject->CompleteWithError(ex);
	}
}

void AsynchronousCommandInvoker::UnlinkTransID(const string& transID)
{
	Lock lock(*this);
	TransIDToWaitMap::iterator found = transIDToWaitMap.find(transID);

	if (found != transIDToWaitMap.end())
		transIDToWaitMap.erase(found);
}

void AsynchronousCommandInvoker::InvokeIOR(const string& command, const string& targetIOR, InvokeWaitObject::Ptr waitObject)
{
	Invoke(command, GetCommandableFromIOR(targetIOR), waitObject);
}

void AsynchronousCommandInvoker::InvokeIOR(const CORBA::Any& command, const string& targetIOR, InvokeWaitObject::Ptr waitObject)
{
	Invoke(command, GetCommandableFromIOR(targetIOR), waitObject);
}

string AsynchronousCommandInvoker::NextTransID()
{
	Lock lock(*this);

	stringstream idstr;
	idstr << prefix << ++nextID;

	return idstr.str();
}

AsynchronousCommandInvoker::ICommandable_var AsynchronousCommandInvoker::GetCommandable(const string& targetName, const string& targetKind)
{
	return broker.GetNamedInstance<ICommandable_var, ICommandable>(targetName.c_str(), targetKind.c_str());
}

AsynchronousCommandInvoker::ICommandable_var AsynchronousCommandInvoker::GetCommandableFromIOR(const string& targetIOR)
{
	return broker.GetObjectFromStringizedName<ICommandable_var, ICommandable>(targetIOR.c_str());
}

void AsynchronousCommandInvoker::lock()
{
	mutex.lock();
}

bool AsynchronousCommandInvoker::try_lock()
{
	return mutex.try_lock();
}

void AsynchronousCommandInvoker::unlock()
{
	mutex.unlock();
}

AsynchronousCommandInvoker::InvokeWaitObject::InvokeWaitObject()
: errPtr(NULL)
, active(false)
{
}

AsynchronousCommandInvoker::InvokeWaitObject::~InvokeWaitObject()
{
}

const AsynchronousCommandInvoker::InvokeWaitObject::ResultList& AsynchronousCommandInvoker::InvokeWaitObject::AwaitCompletion(float numSeconds)
{
	float start = GetSystemUpTimeSeconds();
	float elapsed;

	do
	{
		elapsed = GetSystemUpTimeSeconds()-start;

		float remaining = numSeconds-elapsed;
		unsigned ms = (remaining <= 0) ? 0u : (unsigned) ceil(1000*remaining);

		if (sem.TimedWait(ms))
		{
			if (errPtr)
			{
				if (errPtr == &typeid(CommFailure))
					;
				else if (errPtr == &typeid(NotReady))
					;
				else if (errPtr == &typeid(TooManyConcurrentCommands))
					;
				else if (errPtr == &typeid(UnavailableInPowerOffState))
					;
				else if (errPtr == &typeid(WillCompleteAsynchronously))
					;
				else
				{
					stringstream msg;
					msg << "Re-throwing " << errTypeName << " exception: " << errDetail << " (rethrown as runtime_error)";
					throw runtime_error(msg.str());
				}
			}
			else
				return resultList;
		}

	} while(elapsed > 0);

	throw Timeout("Wait for asynchronous completion of ICommandable::SendCommand timed out");
}

void AsynchronousCommandInvoker::InvokeWaitObject::Complete(Any_var result, bool lastReport)
{
	Lock lock(mutex);

	if (active)
	{
		resultList.push_back(result);

		if (lastReport)
		{
			active = false;
			sem.Post();
		}

		lock.unlock();
		CompletionSignal(*this, result.in(), NULL, "", "", lastReport);
	}
}

void AsynchronousCommandInvoker::InvokeWaitObject::CompleteWithError(CORBAException& corbaEx)
{
	Lock lock(mutex);

	if (active)
	{
		Any_var none;

		errPtr = &typeid(corbaEx);
		errTypeName = corbaEx._name();
		errDetail.clear();
		active = false;
		lock.unlock();

		CompletionSignal(*this, none.in(), errPtr, errTypeName, errDetail, true);
	}
}

void AsynchronousCommandInvoker::InvokeWaitObject::CompleteWithError(exception& ex)
{
	Lock lock(mutex);

	if (active)
	{
		Any_var none;

		errPtr = &typeid(ex);
		errTypeName = errPtr->name();
		errDetail = ex.what();
		active = false;
		lock.unlock();

		CompletionSignal(*this, none.in(), errPtr, errTypeName, errDetail, true);
	}
}

const string& AsynchronousCommandInvoker::InvokeWaitObject::GetTransactionID() const
{
	Lock lock(const_cast<Mutex&>(mutex));
	return transID;
}

void AsynchronousCommandInvoker::InvokeWaitObject::ResetWaitable(const string& _transID)
{
	Lock lock(mutex);

	// reset the semaphore to a waiting state
	while(sem.TryWait())
		;

	// reset parameters
	transID = _transID;
	errPtr = NULL;
	errTypeName.clear();
	errDetail.clear();
	resultList.clear();
	active = true;
}

}
}
