#include "HttpRequest.h"

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

#include <sstream>

HttpRequest::HttpRequest(Verb verb, const std::string& path)
    :   mVerb(verb)
{
    mPreamble.mPath = path;
}

HttpRequest::Verb HttpRequest::getVerb() const
{
    return mVerb;
}

std::string HttpRequest::getPath() const
{
    return mPreamble.mPath;
}

std::string HttpRequest::toString(const std::string& host) const
{
    std::string out;

    if (mVerb == Verb::GET)
    {
        out += "GET";
    }

    auto path = mPreamble.mPath;
    out += " /" + path + " HTTP/" + mHeader.getHttpVersion() + "\n";
    out += "Host: " + host + "\n";
    out += "Accept - Encoding: \n";
    return out;
}

void HttpRequest::fromString(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);
        }
    }
    if (mPreamble.mMethod == "GET")
    {
        mVerb = Verb::GET;
    }
    mHeader.parse(headers);

    mRequiredBytes = 0;
}

std::size_t HttpRequest::requiredBytes() const
{
    return mRequiredBytes;
}
