//-------------------------------------------------------------------------------------------------
// <copyright file="LWSerialPortLua.h" company="LiquidRobotics">
//  Copyright (c) Liquid Robotics Corporation, confidential and proprietary.  All rights reserved. 
// </copyright>
//
// <summary>
//	Declarations for LWSerialPortLua, an implementation of metatable methods exposed
//	to lua as the return value from SMC:NewSerialPort()  It represents the methods of a
//	(simplified) serial port.
// </summary>
//
// <owner>Mike Cookson</owner>
//-------------------------------------------------------------------------------------------------

#ifndef __LWSerialPortLua_h__
#define __LWSerialPortLua_h__

#include "LqrSMACByteArray.h"
#include "LqrSMACSerialPort.h"
#include "LqrSMACSerialListener.h"
#include "LqrSMACLuaInstance.h"
#include "LqrSMACSharedLib.h"
#include "Luna2.h"
#include <boost/shared_ptr.hpp>

class LWControllerBase0;

namespace LiquidRobotics {
namespace LuaWrapper {

class SHARED_LIB_PUBLIC LWSerialPortLua : public boost::noncopyable
{
public:

	typedef LiquidRobotics::SMACFramework::ByteArray ByteArray;
	typedef LiquidRobotics::SMACFramework::ISerialPort ISerialPort;
	typedef LiquidRobotics::SMACFramework::LuaInstance LuaInstance;
	typedef Luna2<LWSerialPortLua> LunaT;
	typedef LunaT::RegType RegType;
	typedef LiquidRobotics::SMACFramework::SerialListener SerialListener;
	typedef std::string string;

	LWSerialPortLua(LuaInstance& _L);
	virtual ~LWSerialPortLua();

	void Initialize(LWControllerBase0* _ctrl, const string& _configName, const string& _luaInstanceName, const string& _portInstanceName);

	static string GetClassName();
	static int GetRegistrations(const RegType*& regBase);
	static void PreRegistration(LuaInstance& L);

	// Lua interface functions for serial port
	int L_GetID(LuaInstance& L);			// GetID <config> <instanceName> (used with callback)
	int L_SetBaudRate(LuaInstance& L);		// SetBaudRate <newBaudRate>
	int L_SetBreak(LuaInstance& L);			// SetBreak
	int L_SetBreakTime(LuaInstance& L);		// SetBreakTime <timeout-millisec>
	int L_Transmit(LuaInstance& L);			// Transmit <bytes>

	// C++ interface functions for serial port
	string GetID() const;
	void SetBaudRate(ISerialPort::BaudRate baudRate);
	void SetBreak();
	void SetBreak(int ms);
	void Transmit(const ByteArray& data);

protected:

	void OnSerialDataReceived(SerialListener& sender, const ByteArray& data);

private:

	static const Luna2<LWSerialPortLua>::RegType registrations[];
	static const size_t registrationCount;

	LWControllerBase0* pController;
	string luaInstanceName;
	string configName;
	string portInstanceName;
	ISerialPort::Ptr sp;
	SerialListener::Ptr serListener;
	SerialListener::ScopedConnectionPtr serListenerConnection;
};

}
}

#endif
