//-------------------------------------------------------------------------------------------------
// <copyright file="LWUnloadLuaCmd.cpp" company="LiquidRobotics">
//  Copyright (c) Liquid Robotics Corporation, confidential and proprietary.  All rights reserved. 
// </copyright>
//
// <summary>
//	Implementation of LWUnloadLuaCmd, a command class that is created from a SendCommand
//	invocation.  Commands are first queued up on a queue and run consecutively on the
//	controller's command thread.  LWUnloadLuaCmd unloads a lua script/instance.
// </summary>
//
// <owner>Mike Cookson</owner>
//-------------------------------------------------------------------------------------------------

#include "LWUnloadLuaCmd.h"
#include "LqrSMACCmdLineParser.h"
#include "LqrSMACLogger.h"
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace LiquidRobotics::SMACFramework;

namespace LiquidRobotics {
namespace LuaWrapper {

LWUnloadLuaCmd::LWUnloadLuaCmd(TCon& _ctrl, const string& _cmd, const string& _instanceName)
: LWConcreteCmd(_ctrl)
, ctrl(_ctrl)
, cmd(_cmd)
, instanceName(_instanceName)
{
}

LWUnloadLuaCmd::~LWUnloadLuaCmd()
{
}

// this method is called by the background thread to execute the command
void LWUnloadLuaCmd::Execute()
{
	try
	{
		SignalStarted();
		ctrl.CloseLua(instanceName);
		SetException(TEx::NoException, "");
	}
	catch(exception& ex)
	{
		const int exNum = TEx::ExceptionToNumber(ex);

		stringstream msg;
		msg << "caught exception " << typeid(ex).name() << " '" << ex.what() << "'";

		SetException(exNum, msg.str());
	}
	catch(...)
	{
		TEx::NotReady exc("");
		const int exNum = TEx::ExceptionToNumber(exc);

		SetException(exNum, "caught unknown exception");
	}
}

// parse the command
LWUnloadLuaCmd::CmdPtr LWUnloadLuaCmd::Parse(const string& arg1, const string& arg2, TCon& ctrl, const CmdLineParser& parser, ParsingContext& context, Logger& logger)
{
	CmdPtr result;
	const int numParams = parser.Count();

	if ((numParams >= 2) && boost::iequals(parser[0], arg1) && boost::iequals(parser[1], arg2))
	{
		stringstream msg;

		switch(numParams)
		{
		case 2:
		{
			msg << "Missing lua instance name parameter in '" << parser.GetOriginalCmdLine() << "'";
			throw invalid_argument(msg.str());
		}

		case 3:
		{
			result.reset(new LWUnloadLuaCmd(ctrl, parser.GetOriginalCmdLine(), parser[2]));
			break;
		}

		default:
		{
			msg << "Too many parameters specified in '" << parser.GetOriginalCmdLine() << "'";
			throw invalid_argument(msg.str());
		}

		}
	}

	return result;
}

}
}
