#include "url.hpp"

namespace Http
{
	bool Url::HasPath() const
	{
		return path.size() > 1;
	}

	bool Url::HasQuery() const
	{
		return query.size() > 1;
	}

	std::string const & Url::GetPath() const
	{
		return path;
	}

	std::string const & Url::GetQuery() const
	{
		return query;
	}

	bool Url::TryParseFromUrlString(std::string urlstring)
	{
		// TODO add % decoding
		unsigned queryPos = 0;
		static std::string const validSpecialCharacters = "-._~:/?#[]@!$&'()*+,;=";
		for(unsigned i = 0; i < urlstring.size(); ++i)
		{
			if (!std::isalnum(urlstring[i]) && validSpecialCharacters.find(urlstring[i]) == std::string::npos)
			{
				return false;
			}
			else if (urlstring[i] == '?' && queryPos == 0)
			{
				queryPos = i;
			}
		}

		if (queryPos == 0)
		{
			path = urlstring;
		}
		else
		{
			path = urlstring.substr(0, queryPos);
			query = urlstring.substr(queryPos, urlstring.size());
		}

		return true;
	}
}