//------------------------------------------------------------------------------
// <copyright file="LqrSMACReaderWriter.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>
// </summary>
//
// <owner></owner>
//------------------------------------------------------------------------------

#include "LqrSMACReaderWriter.h"
#include "LqrSMACTimeCounter.h"
#include <stdexcept>

using namespace std;

namespace LiquidRobotics {
namespace SMACFramework {

ReaderWriterData::ReaderWriterData()
: numReaders(0)
{
}

ReaderWriterData::~ReaderWriterData()
{
}

ReaderWriter::ReaderWriter()
{
	rwData.reset(new ReaderWriterData);
}

ReaderWriter::~ReaderWriter()
{
}

ReaderWriterLock::ReaderWriterLock(ReaderWriter& readerWriter, LockStates action, unsigned timeout, bool throwOnError)
: state(NOT_LOCKED)
, rwData(readerWriter.rwData)
{
	switch(action)
	{
	case NOT_LOCKED:												break;
	case LOCK_FOR_READ:		LockForRead(timeout, throwOnError);		break;
	case LOCK_FOR_WRITE:	LockForWrite(timeout, throwOnError);	break;
	default:				throw invalid_argument("ReaderWriterLock::ReaderWriterLock: action is not a valid enumerated value");
	}
}

ReaderWriterLock::~ReaderWriterLock()
{
	if (state != NOT_LOCKED)
		Unlock();
}

ReaderWriterLock::LockStates ReaderWriterLock::GetState() const
{
	return state;
}

bool ReaderWriterLock::Lock(LockStates action, unsigned timeout, bool throwOnError)
{
	LockableConceptMutex::Lock lock(lockable);
	bool result = false;

	switch(action)
	{
	case NOT_LOCKED:		throw invalid_argument("ReaderWriterLock::Lock: 'not locked' is not a valid action");
	case LOCK_FOR_READ:		result = LockForRead(timeout, throwOnError);	break;
	case LOCK_FOR_WRITE:	result = LockForWrite(timeout, throwOnError);	break;
	default:				throw invalid_argument("ReaderWriterLock::Lock: action is not a valid enumerated value");
	}

	return result;
}

bool ReaderWriterLock::LockForRead(unsigned timeout, bool throwOnError)
{
	LockableConceptMutex::Lock lock(lockable);

	if (state != NOT_LOCKED)
		throw invalid_argument("ReaderWriterLock::LockForRead: this lock is already locked");

	bool result = false;
	TimeCounter timeCounter;
	bool timedOut = false;

	while(!timedOut && !result)
	{
		if (timeout == ReaderWriterDetail::Infinite)
		{
			try			{ rwData->readSem.Wait(); }
			catch(...)	{ if (throwOnError) throw; else return false; }
		}
		else
		{
			bool locked = false;

			try			{ locked = rwData->readSem.TimedWait(timeCounter.Remaining(timeout), throwOnError); }
			catch(...)	{ if (throwOnError) throw; else return false; }

			if (!locked) return false;
		}

		LockableConceptMutex::Lock locked(*rwData);

		if (++rwData->numReaders == 1)
		{
			locked.unlock();

			if (rwData->writeSem.TryWait())
				result = true;

			else
			{
				locked.lock();
				--rwData->numReaders;
				locked.unlock();
				rwData->readSem.Post();

				timedOut = (timeout != ReaderWriterDetail::Infinite) && (timeCounter.Remaining(timeout) > 0);

				if (!timedOut)
					usleep(10*1000);
			}
		}
		else
			result = true;
	}

	if (result)
	{
		state = LOCK_FOR_READ;
		rwData->readSem.Post();
	}

	return result;
}

bool ReaderWriterLock::LockForWrite(unsigned timeout, bool throwOnError)
{
	LockableConceptMutex::Lock lock(lockable);

	if (state != NOT_LOCKED)
		throw invalid_argument("ReaderWriterLock::LockForWrite: this lock is already locked");

	bool result = false;
	TimeCounter timeCounter;
	bool timedOut = false;

	while(!timedOut && !result)
	{
		if (timeout == ReaderWriterDetail::Infinite)
		{
			try			{ rwData->writeSem.Wait(); }
			catch(...)	{ if (throwOnError) throw; else break; }
		}
		else
		{
			bool locked = false;

			try			{ locked = rwData->writeSem.TimedWait(timeCounter.Remaining(timeout), throwOnError); }
			catch(...)	{ if (throwOnError) throw; else break; }

			if (!locked) return false;
		}

		if (rwData->readSem.TryWait())
			result = true;

		else
		{
			rwData->writeSem.Post();
			timedOut = (timeout != ReaderWriterDetail::Infinite) && (timeCounter.Remaining(timeout) > 0);

			if (!timedOut)
				usleep(10*1000);
		}
	}

	if (result)
		state = LOCK_FOR_WRITE;

	return result;

}

bool ReaderWriterLock::ReadLockToWriteLock(unsigned timeout, bool throwOnError)
{
	LockableConceptMutex::Lock lock(lockable);

	if (state != LOCK_FOR_READ)
		throw invalid_argument("ReaderWriterLock::ReadLockToWriteLock: this lock is not locked for read");

	bool result = false;
	TimeCounter timeCounter;

	if (timeout == ReaderWriterDetail::Infinite)
	{
		try 		{ rwData->writeSem.Wait(); result = true; }
		catch(...)	{ if (throwOnError) throw; }
	}
	else
	{
		try 		{ result = rwData->writeSem.TimedWait(timeCounter.Remaining(timeout), throwOnError); }
		catch(...)	{ if (throwOnError) throw; else return false; }
	}

	if (result)
	{
		state = LOCK_FOR_WRITE;
		LockableConceptMutex::Lock locked(*rwData);
		++rwData->numReaders;
	}

	return result;
}

bool ReaderWriterLock::Unlock()
{
	LockableConceptMutex::Lock lock(lockable);

	switch(state)
	{
	case LOCK_FOR_READ:		{ LockableConceptMutex::Lock locked(*rwData); if (rwData->numReaders && !--rwData->numReaders) rwData->writeSem.Post(); break; }
	case LOCK_FOR_WRITE:	rwData->readSem.Post(); rwData->writeSem.Post(); break;
	case NOT_LOCKED:		break;
	}

	state = NOT_LOCKED;
	return true;
}

bool ReaderWriterLock::WriteLockToReadLock(bool throwOnError)
{
	LockableConceptMutex::Lock lock(lockable);

	if (state != LOCK_FOR_WRITE)
		throw invalid_argument("ReaderWriterLock::WriteLockToReadLock: this lock is not locked for write");

	LockableConceptMutex::Lock locked(*rwData);
	++rwData->numReaders;
	rwData->writeSem.Post();
	return true;
}

void ReaderWriterLock::lock()
{
	Lock(LOCK_FOR_READ, ReaderWriterDetail::Infinite, true);
}

bool ReaderWriterLock::try_lock()
{
	return Lock(LOCK_FOR_READ, 0, false);
}

void ReaderWriterLock::unlock()
{
	Unlock();
}

}
}
