
#include <unistd.h>

#include "processor.h"
#include "message.h"

#include "http_response.h"

bool
http_response_sendSimpleMessage (Processor *processor, Message *requestMessage)
{
    Message *responseMessage;
    bool ret;

    ret = processor_sendMessage (processor, requestMessage, &responseMessage);

    if (ret == false)
    {
        logFmsg (CONT_LOG_ERROR, "%d/Could not send message.", getpid());
    }
    else 
    {
        if (message_getType (responseMessage) == MessageTypeErrorResponse)
        {
            logFmsg (CONT_LOG_DEBUG, "causality-client: An error was returned.");

            message_print (responseMessage);

            ret = false;
        }
        else
        {
            ret = true;
        }
        
        message_destroy (responseMessage);
    }

    return (ret);
}

bool
http_response_sendFinishMessage (Processor *processor, const char *token, 
        int returnStatus)
{
    Message *requestMessage;
    Message *responseMessage;
    bool ret;

    requestMessage= message_newRequest ("HttpFinish");

    message_setParameter (requestMessage, "token", token);

    message_setParameterInt (requestMessage, "returnStatus", returnStatus);

    ret = processor_sendMessage (processor, requestMessage, &responseMessage);

    if (ret == false)
    {
        logFmsg (CONT_LOG_ERROR, "%d/Could not send message.", getpid());
    }
    else 
    {
        if (message_getType (responseMessage) == MessageTypeErrorResponse)
        {
            logFmsg (CONT_LOG_DEBUG, "causality-client: An error was returned.");

            message_print (responseMessage);

            ret = false;
        }
        else
        {
            ret = true;
        }
        
        message_destroy (responseMessage);
    }

    message_destroy (requestMessage);

    return (ret);
}

bool
http_response_sendReadEntityBody (Processor *processor, const char *token, dynTstring *entity)
{
    Message *requestMessage;
    Message *responseMessage;
    bool ret;

    requestMessage= message_newRequest ("HttpReadEntityBody");

    message_setParameter (requestMessage, "token", token);

    ret = processor_sendMessage (processor, requestMessage, &responseMessage);

    if (ret == false)
    {
        logFmsg (CONT_LOG_ERROR, "%d/Could not send message.", getpid());
    }
    else 
    {
        if (message_getType (responseMessage) == MessageTypeErrorResponse)
        {
            ret = false;
        }
        else
        {
            ret = true;

            dynFappend_string (entity, 
                    message_getParameterString (responseMessage, "data"));
        }
        
        message_destroy (responseMessage);
    }

    message_destroy (requestMessage);

    return (ret);
}


