//-------------------------------------------------------------------------------------------------
// <copyright file="LWTimerLua.cpp" company="LiquidRobotics">
//  Copyright (c) Liquid Robotics Corporation, confidential and proprietary.  All rights reserved. 
// </copyright>
//
// <summary>
//	Implementation of LWTimerLua, an implementation of metatable methods exposed to
//	lua as the return value from SMC:NewTimer()  It represents the methods of an
//	interval timer.
// </summary>
//
// <owner>Mike Cookson</owner>
//-------------------------------------------------------------------------------------------------

#include "LWConcreteCmd.h"
#include "LWTimerLua.h"

using namespace std;

namespace LiquidRobotics {
namespace LuaWrapper {

const LWTimerLua::RegType LWTimerLua::registrations[] =
{
	{ "GetID",				&LWTimerLua::L_GetID },
};

const size_t LWTimerLua::registrationCount = sizeof(registrations)/sizeof(registrations[0]);

LWTimerLua::LWTimerLua(LuaInstance& _L)
: pController(NULL)
{
}

LWTimerLua::~LWTimerLua()
{
	conn.reset();

	if (tcol && timer)
		tcol->RemoveTimer(timer);

	timer.reset();
}

void LWTimerLua::Initialize(LWControllerBase0* _ctrl, TimerCollectionBasePtr _tcol, const string& _luaInstanceName, const string& _timerInstanceName, unsigned _ms)
{
	pController = _ctrl;
	tcol = _tcol;
	luaInstanceName = _luaInstanceName;
	timerInstanceName = _timerInstanceName;

	if (tcol)
	{
		Timer* pTimer = new TimerWithString(timerInstanceName, _ms);

		try
		{
			conn = pTimer->SubscribeTimerExpired(boost::bind(&LWTimerLua::OnTimerExpired, this, _1));
			timer = tcol->InsertTimer(pTimer);
		}
		catch(...)
		{
			delete pTimer;
			throw;
		}
	}
}

string LWTimerLua::GetClassName()
{
	return "SMCTimer";
}

int LWTimerLua::GetRegistrations(const RegType*& regBase)
{
	regBase = registrations;
	return registrationCount;
}

void LWTimerLua::PreRegistration(LuaInstance& L)
{
}

// Lua interface functions for serial port
int LWTimerLua::L_GetID(LuaInstance& L)
{
	L.pushlstring(GetID());
	return 1;
}

// C++ interface functions for serial port
string LWTimerLua::GetID() const
{
	return timerInstanceName;
}

void LWTimerLua::OnTimerExpired(Timer& sender)
{
	if (pController)
		pController->ForwardTimeout(luaInstanceName, timerInstanceName);
}

}
}
