
#include "mecha.h"
#include "responseholderlist.h"
#include "command_handlers.h"
#include "processor.h"

#include "serialization.h"

#include "message_processor.h"

struct s_MessageProcessor
{
    dynTstring *message;
    ResponseHolderList *responses;
    CommandHandlers *commandHandlers;
    Processor *processor;
};

MessageProcessor *
message_processor_new (dynTstring *message, ResponseHolderList *responses, 
        CommandHandlers *commandHandlers, Processor *processor)
{
    MessageProcessor *mp = malloc (sizeof (MessageProcessor));

    mp->message = message;
    mp->responses = responses;
    mp->commandHandlers = commandHandlers;
    mp->processor = processor;

    return (mp);
}

void
message_processor_destroy (void *ptr)
{
    MessageProcessor *mp = (MessageProcessor *) ptr;

    dynFfree (mp->message);

    free (mp);
}

void
message_processor_process (void *context)
{
    MessageProcessor *mp = (MessageProcessor *) context;
    Message *message;
    bool ret;

    ret = serialization_deserializeType ("Message", &message, mp->message);

    if (ret == false)
    {
        logFmsg (CONT_LOG_ERROR, "Failed to deserialize message: %s", dynFgetstr (mp->message));
    }
    else
    {
        if (message_getType (message) == MessageTypeRequest)
        {
            /* message will be destroyed when it is done being used */
            command_handlers_processMessage (mp->commandHandlers, message, mp->processor);
        }
        else
        {
            responseholderlist_setResponse (mp->responses, message);
        }
    }

    message_processor_destroy (mp);
}

