#include "HttpRequest.h"

#include "StringUtils.h"

#include <sstream>

void HttpRequest::parseMessage(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)
		{
			parseFirstLine(buffer);
			firstLine = false;
		}
		else
		{
			headers.push_back(buffer);
		}
	}
	mHeader.parse(headers);
}

void HttpRequest::parseFirstLine(const std::string& line)
{
	bool inPath{false};
	bool inMethod{true};
	bool inProtocol{false};

	for (std::size_t idx=0; idx<line.size();idx++)
	{
		const auto c = line[idx];
		if (inPath)
		{
			if (StringUtils::IsSpace(c))
			{
				inPath = false;
				inMethod = true;
			}
			else
			{
				mMethod.push_back(c);
			}
		}
		else if (inMethod)
		{
			if (StringUtils::IsSpace(c))
			{
				inMethod = false;
				inProtocol = true;
			}
			else
			{
				mPath.push_back(c);
			}
		}
		else if (inProtocol)
		{
			mProtocolVersion.push_back(c);
		}
	}
}
