//----------------------------------------------------------------------------------
// <copyright file="SSQEnqueueCmd.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>
// 	Declaration of SSQEnqueueCmd, a queue-able item that executes the EnqueueMessage
//  on the controller.
// </summary>
//
// <owner>Mike Cookson</owner>
//----------------------------------------------------------------------------------

#include "SSQEnqueueCmd.h"
//#include "MicrostrainControllerPersistSettings.h"
#include "LqrSMACCmdLineParser.h"
#include "LqrSMACBooleanParser.h"
#include "LqrSMACByteArray.h"
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace LiquidRobotics::SMACFramework;

namespace LiquidRobotics {
namespace SimpleSBDQueue {

SSQEnqueueCmd::SSQEnqueueCmd(TCon& _ctrl, const string& _cmd, Logger& _logger, bool _mbCheck,
        const ByteArray& _message, const PriorityType _priority, const SenderIDType _senderID,
        const SenderTransactionType _senderTrans, const QueuePosition _queuePos,
        const TTLType _ttl)
: SSQConcreteCmd(_ctrl)
, ctrl(_ctrl)
, cmd(_cmd)
, logger(_logger)
, mbCheck(_mbCheck)
, message(_message.begin(), _message.end())
, priority(_priority)
, senderID(_senderID)
, senderTrans(_senderTrans)
, queuePos(_queuePos)
, ttl(_ttl)
{
}

SSQEnqueueCmd::~SSQEnqueueCmd()
{
}

// this method is called by the background thread to execute the command
void SSQEnqueueCmd::Execute()
{
	SignalStarted();

	try
	{
        if (mbCheck)
            ctrl.RequestMailboxCheck();
        else
            ctrl.EnqueueMessage(priority, message, senderID, senderTrans, queuePos, ttl);
	}
	catch(exception& ex)
	{
		stringstream msg;
		msg << "Caught exception while stopping: " << typeid(ex).name() << " '" << ex.what() << "'";

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

// parse the command
SSQEnqueueCmd::CmdPtr SSQEnqueueCmd::Parse(const string& arg1, const string& arg2, bool mbCheck, TCon& ctrl, const CmdLineParser& parser, ParsingContext& context, Logger& logger)
{
	CmdPtr result;
	const CmdLineParser::StringArray& tokens = parser.GetTokens();
    const size_t numTokens = tokens.size();

	if ((numTokens >= 2)
	 && boost::iequals(tokens[0], arg1)
	 && boost::iequals(tokens[1], arg2))
	{
		if (mbCheck && (numTokens > 2))
			throw invalid_argument("Too many arguments");

        PriorityType priority = (PriorityType) 3;
        ByteArray message;
        SenderIDType senderID = ~((SenderIDType) 0);
        SenderTransactionType senderTrans = ~((SenderTransactionType) 0);
        QueuePosition queuePos = SSQControllerBase0::QUEUE_END;
        TTLType ttl = (TTLType) 0;
        bool messageSpecified = 0;
        const size_t numTokens = tokens.size();

        for (unsigned tokenIdx = 2; tokenIdx < numTokens; ++tokenIdx)
        {
            const string& token = tokens[tokenIdx];
            const size_t tokenEq = token.find('=');

            if (tokenEq == string::npos)
            {
                if (messageSpecified)
                    throw invalid_argument("Message was specified twice");
                else if (token.length() & 1)
                    throw invalid_argument("Message is not a valid hex string");
                else
                {
                    message.FromHexString(token);
                    messageSpecified = true;
                }
            }
            else
            {
                const string tag = token.substr(0, tokenEq);
                const string val = token.substr(tokenEq+1);

                if (boost::iequals(tag, "--priority"))
                {
                    try { priority = boost::lexical_cast<PriorityType>(val); }
                    catch(...) { throw invalid_argument("Failed to convert argument to --priority"); }
                }
                else if (boost::iequals(tag, "--senderid"))
                {
                    try { senderID = boost::lexical_cast<SenderIDType>(val); }
                    catch(...) { throw invalid_argument("Failed to convert argument to --senderid"); }
                }
                else if (boost::iequals(tag, "--sendertransaction"))
                {
                    try { senderTrans = boost::lexical_cast<SenderTransactionType>(val); }
                    catch(...) { throw invalid_argument("Failed to convert argument to --sendertransaction"); }
                }
                else if (boost::iequals(tag, "--queue"))
                {
                    if (boost::iequals(val, "end"))
                        queuePos = SSQControllerBase0::QUEUE_END;
                    else if (boost::iequals(val, "front"))
                        queuePos = SSQControllerBase0::QUEUE_FRONT;
                    else if (boost::iequals(val, "latest"))
                        queuePos = SSQControllerBase0::QUEUE_LATEST_AT_FRONT;
                    else
                        try { queuePos = (QueuePosition) boost::lexical_cast<unsigned>(val); }
                        catch(...) { throw invalid_argument("Failed to convert argument to --queue"); }
                }
                else if (boost::iequals(tag, "--ttl"))
                {
                    try { ttl = boost::lexical_cast<TTLType>(val); }
                    catch(...) { throw invalid_argument("Failed to convert argument to --ttl"); }
                }
            }

        }

        if (!mbCheck && !messageSpecified)
            throw runtime_error("Message was not specified");

		result.reset(new SSQEnqueueCmd(ctrl, parser.GetOriginalCmdLine(), logger, mbCheck, message, priority, senderID, senderTrans, queuePos, ttl));
	}

	return result;
}

}
}
