#include "request.hpp"
#include <sstream>

namespace Http
{
	template<class T>
	T ToEnum(std::string const & str, std::vector<std::string> const & enumStrings)
	{
		for(unsigned i = 0; i < enumStrings.size(); ++i)
		{
			if (str.compare(enumStrings[i]) == 0)
			{
				return static_cast<T>(i);
			}
		}

		return static_cast<T>(-1);
	}

	void Request::Deserialize(std::vector<char> const & bytes, Logger & logger)
	{
		// TODO serialize more than just the start
		std::stringstream ss(std::string(bytes.begin(), bytes.end()));
		
		std::string requestTypeString;
		ss >> requestTypeString;
		type = ToEnum<HttpRequest::Type>(requestTypeString, HttpRequest::typeStrings);
		if (type == HttpRequest::Type::UNKNOWN)
		{
			logger.Error("Request::Deserialize: Bad request type");
			return;
		}

		std::string rawUrl;
		ss >> rawUrl;
		if(!url.TryParseFromUrlString(rawUrl))
		{
			logger.Error("Request::Deserialize: Bad url in request");
			type = HttpRequest::Type::UNKNOWN;
			return;
		}

		std::string httpProtocolString;
		ss >> httpProtocolString;
	}
}
