#include "HttpClient.h"

#include "FileLogger.h"

#ifdef _WIN32
#include "WinsockClient.h"
#else
#include "UnixSocketClient.h"
#endif

HttpClient::HttpClient()
{
#ifdef _WIN32
    mSocketClient = std::make_unique<WinsockClient>();
#else
    mSocketClient = std::make_unique<UnixSocketClient>();
#endif
}

HttpResponse HttpClient::makeRequest(const HttpRequest& request, const Address& address)
{
    PlatformSocketClient::Address socket_address;
    socket_address.mHost = address.mHost;
    socket_address.mPort = address.mPort;
    socket_address.mPrefix = address.mPrefix;

    const auto message = request.toString(address.mHost);

    MLOG_INFO("Output http request: " << message);

    auto socket_response = mSocketClient->request(socket_address, message);

    HttpResponse response;
    if (socket_response.mStatus == PlatformSocketClient::Result::Status::OK)
    {
        response.fromMessage(socket_response.mBody);
    }
    else
    {
        MLOG_ERROR("Http request client error: " << socket_response.mErrorMessage << " | with code: " << socket_response.mErrorCode);

        HttpResponse::ClientError error;
        error.mMessage = socket_response.mErrorMessage;
        error.mCode = socket_response.mErrorCode;
        response.setClientError(error);
    }
    return response;
}
