//------------------------------------------------------------------------------
// <copyright file="LqrSMACSerialListener.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 the SerialListener class, which spawns a thread and reads
//   incoming data, firing events from the background thread for received data
//   packets.
// </summary>
//
// <owner>Mike Cookson</owner>
//------------------------------------------------------------------------------

#include "LqrSMACSerialListener.h"
#include "LqrSMACSerialListenerSettings.h"

using namespace std;
using namespace boost::posix_time;

namespace LiquidRobotics {
namespace SMACFramework {

const string alreadyInitialized("This object instance was already initialized");
const string notInitialized("This object instance has not been initialized or was shut down");

IMPLEMENT_INNER_EXCEPTION(SerialListener,AlreadyInitialized,std::logic_error);
IMPLEMENT_INNER_EXCEPTION(SerialListener,NotInitialized,std::logic_error);

SerialListener::SerialListener(ISerialPort& _sp, size_type _maxRead, TimeSpan _readTimeout)
: sp(_sp)
, maxRead(_maxRead)
, readTimeout(_readTimeout)
, pThread(NULL)
, signalStop(false)
, shutDown(false)
{
}

SerialListener::SerialListener(ISerialPort& _sp, const SerialListenerSettings& settings)
: sp(_sp)
, maxRead(settings.GetMaxReadSize())
, readTimeout(settings.GetIntercharacterGapTimeout())
, pThread(NULL)
, signalStop(false)
, shutDown(false)
{
}

SerialListener::~SerialListener()
{
	if (pThread)
	{
		pThread->join();
		pThread = NULL;
	}
}

void SerialListener::Initialize()
{
	if (pThread || shutDown)
		throw AlreadyInitialized(alreadyInitialized);

	pThread = new boost::thread(boost::ref(*this));
}

void SerialListener::Shutdown()
{
	if (pThread && !shutDown)
	{
		signalStop = true;
		pThread->join();
		shutDown = true;
		pThread = NULL;
	}
}

void SerialListener::operator()()
{
	bool reading = false;
	const TimeSpan longTime = milliseconds(500);

	while(!signalStop)
	{
    	ByteArray ba;
		bool readable = true;
		bool writeable = false;
		TimeSpan ts = reading ? readTimeout : longTime;

	    sp.WaitForPortState(ts, readable, writeable);

	    if (readable)
	    	sp.ReadWithIntervalTimer(ba, maxRead, readTimeout);

	    if (ba.size() || reading)
		{
    		ILockableConcept::Lock firingLock(firingMutex);
    		hereIsSerialData_Signal(*this, ba);
    		firingLock.unlock();

			reading = !!ba.size();
		}
	}
}

SerialListener::ScopedConnectionPtr SerialListener::Subscribe(T_HereIsSerialData_Signal::slot_type slot)
{
	ScopedConnectionPtr result;
	result.reset(new ScopedConnection(hereIsSerialData_Signal.connect(slot)));
	return result;
}

ILockableConcept& SerialListener::FiringMutex()
{
	return firingMutex;
}

}
}
