#include "HttpResponse.h"

#include "StringUtils.h"
#include "HttpParser.h"

#include <sstream>

HttpResponse::HttpResponse()
    :   mStatusCode(200),
        mResponseReason("OK"),
        mBody()
{

}

HttpResponse::~HttpResponse()
{

}

const HttpHeader& HttpResponse::getHeader() const
{
    return mHeader;
}

unsigned short HttpResponse::getStatusCode() const
{
    return mStatusCode;
}

const std::string& HttpResponse::getBody() const
{
    return mBody;
}

void HttpResponse::setBody(const std::string& body)
{
    mBody = body;
}

void HttpResponse::fromMessage(const std::string& message)
{
    std::stringstream ss(message);

    std::string buffer;
    bool firstLine{ true };

    std::vector<std::string> headers;
    while (std::getline(ss, buffer, '\n'))
    {
        if (firstLine)
        {
            HttpParser::parsePreamble(buffer, mPreamble);
            firstLine = false;
        }
        else
        {
            headers.push_back(buffer);
        }
    }
    mHeader.parse(headers);
}

unsigned HttpResponse::getBodyLength() const
{
    return unsigned(mBody.length());
}

void HttpResponse::setClientError(const ClientError& error)
{
    mClientError = error;
}

std::string HttpResponse::getHeaderString() const
{
    std::string header = "HTTP/" + mHeader.getHttpVersion() + " " + std::to_string(mStatusCode) + " " + mResponseReason + "\n";
    header += "Content-Type: " + mHeader.getContentType() + "\n";
    header += "Content-Length: " + std::to_string(getBodyLength()) + "\n";
    return header;
}

const std::string& HttpResponse::getResponseReason() const
{
    return mResponseReason;
}

std::string HttpResponse::toString() const
{
    return getHeaderString() + "\n\n" + mBody;
}

void HttpResponse::setStatusCode(unsigned short code)
{
    mStatusCode = code;
}

void HttpResponse::setResponseReason(const std::string& reason)
{
    mResponseReason = reason;
}
