
#include <stdlib.h>

#include "mecha.h"

#include "command_handlers.h"
#include "processor.h"
#include "request_dispatcher.h"

#include "request_handler_entry.h"

#include "threadpool.h"

struct s_CommandHandlers
{
    hshTvoid_list *handlers;
};

CommandHandlers *
command_handlers_new()
{
    CommandHandlers *reqs = malloc (sizeof (CommandHandlers));

    reqs->handlers = hshFvoid_init (request_handler_entry_destroy);

    return (reqs);
}

void
command_handlers_destroy (void *ptr)
{
    CommandHandlers *reqs = (CommandHandlers *) ptr;

    hshFvoid_destroy (reqs->handlers);

    free (reqs);
}

bool
command_handlers_addHandler (CommandHandlers *reqs, const CommandHandler *handler, void *context)
{
    RequestHandlerEntry *entry = request_handler_entry_new (handler, context);

    if (hshFvoid_add (reqs->handlers, handler->commandName, entry))
    {
        return (true);
    }
    else
    {
        return (false);
    }
}

void
command_handlers_processMessage (CommandHandlers *reqs, Message *message, Processor *processor)
{
    RequestDispatcher *dispatcher;
    RequestHandlerEntry *handlerEntry;

    handlerEntry = (RequestHandlerEntry *) hshFvoid_find (reqs->handlers, 
            message_getCommand (message));

    dispatcher = request_dispatcher_new (processor, handlerEntry, message);

    threadpool_queueUserWorkItem (
            threadpool_getInstance(), request_dispatcher_process, dispatcher);
}

