//-------------------------------------------------------------------------------------------------
// <copyright file="LWAsynchScriptContextLua.cpp" company="LiquidRobotics">
//  Copyright (c) Liquid Robotics Corporation, confidential and proprietary.  All rights reserved. 
// </copyright>
//
// <summary>
//	Implementation of LWAsynchScriptContextLua class, an implementation of metatable
//	methods exposed to lua.  The context represents a command invocation: whenever
//	a lua method is invoked as a command, the global SMCContext variable is set to
//	an instance of LWAsynchScriptContextLua.  Methods that want to appear to be
//	synchronous (i.e. which hold up execution of subsequent commands until they
//	complete asynchronously) make a copy of SMCContext and call the SetAsynch member.
//	ReportComplete is called when the method is actually complete.
// </summary>
//
// <owner>Mike Cookson</owner>
//-------------------------------------------------------------------------------------------------

#include "LWAsynchScriptContextLua.h"

using namespace std;

namespace LiquidRobotics {
namespace LuaWrapper {

const Luna2<LWAsynchScriptContextLua>::RegType LWAsynchScriptContextLua::registrations[] =
{
	{ "AppendOutput", 		&LWAsynchScriptContextLua::AppendOutput },
	{ "ReportComplete", 	&LWAsynchScriptContextLua::ReportComplete },
	{ "SetAsynch",			&LWAsynchScriptContextLua::SetAsynch },
	{ "SetSuccessFlag",		&LWAsynchScriptContextLua::SetSuccessFlag },
};

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

LWAsynchScriptContextLua::LWAsynchScriptContextLua(LuaInstance& L)
{
}

LWAsynchScriptContextLua::~LWAsynchScriptContextLua()
{
}

string LWAsynchScriptContextLua::GetClassName()
{
	return "SMCContextClass";
}

int LWAsynchScriptContextLua::GetRegistrations(const Luna2<LWAsynchScriptContextLua>::RegType*& regBase)
{
	regBase = registrations;
	return registrationCount;
}

void LWAsynchScriptContextLua::PreRegistration(LuaInstance& L)
{

}

int LWAsynchScriptContextLua::AppendOutput(LuaInstance& L)
{
	if (L.gettop() >= 1)
	{
		LuaInstance::StringPtr outputStr = L.tolstring(-1);

		if (outputStr)
		{
			Event evt(Event::AppendOutput, *outputStr);

			sig(*this, evt);
		}
	}

	return 0;
}

int LWAsynchScriptContextLua::ReportComplete(LuaInstance& L)
{
	Event evt(Event::ReportComplete);

	sig(*this, evt);
	return 0;
}

int LWAsynchScriptContextLua::SetAsynch(LuaInstance& L)
{
	Event evt(Event::SetAsynch);

	sig(*this, evt);
	return 0;
}

int LWAsynchScriptContextLua::SetSuccessFlag(LuaInstance& L)
{
	if (L.gettop() >= 1)
	{
		bool newStatus = L.toboolean(-1);
		Event evt(Event::SetSuccessFlag, newStatus);
		sig(*this, evt);
	}

	return 0;
}

LWAsynchScriptContextLua::ScopedConnectionPtr LWAsynchScriptContextLua::Subscribe(NotifySignalType::slot_type slot)
{
	ScopedConnectionPtr result;
	result.reset( new ScopedConnection(sig.connect(slot)) );
	return result;
}

}
}
