
#include <assert.h>

#include "processor.h"
#include "http_request_list.h"
#include "http_request_handler.h"

#include "command.h"

static const char *command_HttpRequestStart_RequiredParameters[] = { "token", "variables", "headers", "remoteIP", NULL };
static const char *command_HttpRequestStart_OptionalParameters[] = { "method", "uri", "protocol", "query", NULL };
CommandHandler command_HttpRequestStart = { "HttpRequestStart", http_request_handler_handleRequest,
    command_HttpRequestStart_RequiredParameters, command_HttpRequestStart_OptionalParameters };

static const char *command_HttpRequestPing_RequiredParameters[] = { "token", NULL };
static const char *command_HttpRequestPing_OptionalParamaters[] = { NULL };
CommandHandler command_HttpRequestPing = { "HttpRequestPing", http_request_handler_handlePing,
    command_HttpRequestPing_RequiredParameters, command_HttpRequestPing_OptionalParamaters };

static Message *
http_request_handler_createResponseMessage (Message *requestMessage)
{
    Message *responseMessage = message_makeResponse (requestMessage);

    message_setParameter (responseMessage, "message", "Request Queued.");

    return (responseMessage);
}

Message *
http_request_handler_handleRequest (void *context, Message *requestMessage)
{
    Processor *proc = (Processor *) context;
    HttpRequestList *handlerList = http_request_list_getRequestList();
    HttpRequest *request = http_request_new (requestMessage, proc);

    http_request_list_addRequest (handlerList, request);

    return (http_request_handler_createResponseMessage (requestMessage));
}

Message *
http_request_handler_handlePing (MECHA_UNUSED void *context, Message *requestMessage)
{
    HttpRequestList *handlerList = http_request_list_getRequestList();
    const char *token;

    token = message_getParameter (requestMessage, "token");

    if (http_request_list_containsRequest (handlerList, token))
    {
        Message *responseMessage = message_makeResponse (requestMessage);

        message_setParameter (responseMessage, "message", "Request found.");

        return (responseMessage);
    }
    else
    {
        Message *responseMessage = message_makeErrorResponse (requestMessage);

        message_setParameter (responseMessage, "message", "Request not found.");

        return (responseMessage);
    }
}

