//-----------------------------------------------------------------------------------
// <copyright file="LqrSMACQueueWorkerBase.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 of QueueWorkerBase, the base class for the QueueWorker template
//   class, a worker thread that enqueues work items and then fires events or exposes
//   member functions to handle the work items.
// </summary>
//
// <owner>Mike Cookson</owner>
//-----------------------------------------------------------------------------------

#include "LqrSMACQueueWorker.h"
#include <sstream>

using namespace std;

namespace LiquidRobotics {
namespace SMACFramework {

IMPLEMENT_INNER_EXCEPTION(QueueWorkerBase, AlreadyInitialized, std::runtime_error);
IMPLEMENT_INNER_EXCEPTION(QueueWorkerBase, NotInitialized, std::runtime_error);
IMPLEMENT_INNER_EXCEPTION(QueueWorkerBase, ShutdownRequested, std::runtime_error);

QueueWorkerBase::QueueWorkerBase()
: initialized(false)
, shutDown(false)
{
}

QueueWorkerBase::~QueueWorkerBase()
{
	if (initialized && !shutDown)
		_Shutdown();
}

void QueueWorkerBase::Initialize()
{
	Lock lock(*this);

	CheckState(true);
	thd.reset(new Thread(boost::bind(&QueueWorkerBase::BackgroundThreadFunc, this)));
	initialized = true;
}

LockableConceptMutex& QueueWorkerBase::GetFiringMutex()
{
	return firingMutex;
}

bool QueueWorkerBase::IsInitialized()
{
	return initialized;
}

bool QueueWorkerBase::IsShutdown()
{
	return shutDown;
}

void QueueWorkerBase::Shutdown()
{
	Lock lock(*this);
	_Shutdown(&lock);
}

QueueWorkerBase::ScopedConnectionPtr QueueWorkerBase::SubscribeReadTimeout(ReadTimeoutSignalType::slot_type slot)
{
	ScopedConnectionPtr result;
	result.reset(new ScopedConnection(readTimeoutSignal.connect(slot)));
	return result;
}

QueueWorkerBase::ScopedConnectionPtr QueueWorkerBase::SubscribeShutdownWarning(ShutdownWarningSignalType::slot_type slot)
{
	ScopedConnectionPtr result;
	result.reset(new ScopedConnection(shutdownWarningSignal.connect(slot)));
	return result;
}

QueueWorkerBase::ScopedConnectionPtr QueueWorkerBase::SubscribeWakeup(WakeupSignalType::slot_type slot)
{
	ScopedConnectionPtr result;
	result.reset(new ScopedConnection(wakeupSignalType.connect(slot)));
	return result;
}

void QueueWorkerBase::BackgroundThreadFunc()
{
	QueueEntryType qe;
	int readTimeout;

	while(readTimeout = DetermineReadTimeout(),
		  qe = ReadQueueEntry(readTimeout),
		  qe != ET_SHUTDOWN)
	{
		switch(qe)
		{
		case ET_TIMEOUT:			OnAnnounceTimeout();		break;
		case ET_WAKEUP:				OnAnnounceWakeup();			break;
		default:												break;
		}
	}
}

int QueueWorkerBase::DetermineReadTimeout()
{
	return -1;
}

void QueueWorkerBase::OnAnnounceShutdownWarning()
{
	LockableConceptMutex::Lock lock(firingMutex);
	shutdownWarningSignal(*this);
}

void QueueWorkerBase::OnAnnounceTimeout()
{
	LockableConceptMutex::Lock lock(firingMutex);
	readTimeoutSignal(*this);
}

void QueueWorkerBase::OnAnnounceWakeup()
{
	LockableConceptMutex::Lock lock(firingMutex);
	wakeupSignalType(*this);
}

bool QueueWorkerBase::CheckState(bool isInit, bool throwOnError)
{
	int errNum = 0;

	if (isInit && initialized)
		errNum = 1;
	else if (shutDown)
		errNum = 2;
	else if (!isInit && !initialized)
		errNum = 3;

	if (throwOnError)
	{
		string objType = typeid(*this).name();

		stringstream stm;

		switch(errNum)
		{
		case 1:

			stm << objType << " instance is already initialized";
			throw AlreadyInitialized(stm.str());

		case 2:

			stm << objType << " instance has been shut down";
			throw ShutdownRequested(stm.str());

		case 3:

			stm << objType << " instance has not been initialized";
			throw NotInitialized(stm.str());
		}
	}

	return !errNum;
}

void QueueWorkerBase::_Shutdown(Lock* pLock)
{
	if (!initialized || shutDown)
		return;

	shutDown = true;
	if (pLock) pLock->unlock();
	OnAnnounceShutdownWarning();
	WriteQueueEntry(ET_SHUTDOWN);
	if (thd) thd->join();
	thd.reset();
}

}
}
