
#include "utils.hpp"

std::vector<std::string> split(std::string input, char delimiter)
{
    std::vector<std::string>	answer;
    std::stringstream			ss(input);
    std::string					temp;
 
    while (getline(ss, temp, delimiter))
        answer.push_back(temp);
 
    return answer;
}

std::string	trim(std::string str, char c)
{
	str = str.substr(str.find_first_not_of(c));
	str = str.substr(0, str.find_last_not_of(c) + 1);

	return str;
}

std::string	itos(int n)
{
	std::stringstream	strs;

	strs << n;
	return ( strs.str() );
}

bool	isNumeric(std::string str)
{
	for (size_t i = 0; i < str.length(); i++)
	{
		if (std::isdigit(str[i]) == false)
			return false;
	}
	return true;
}

bool	isNumeric_btw(int low, int high, std::string str)
{
	for (size_t i = 0; i < str.length(); i++)
	{
		if (std::isdigit(str[i]) == false)
			return false;
	}
	int n = std::atoi(str.c_str());
	if (n < low || n > high)
		return false;
	return true;
}

http_method	str_to_http_method(std::string &str)
{
	if (str == "GET")
		return GET;
	else if (str == "POST")
		return POST;
	else if (str == "DELETE")
		return DELETE;
	return UNKNOWN;
}

std::string	http_methods_to_str(unsigned int methods)
{
	std::string	str;

	if (methods & GET)
		str.append("GET");
	if (methods & POST)
	{
		if (!str.empty())
			str.append(", ");
		str.append("POST");
	}
	if (methods & DELETE)
	{
		if (!str.empty())
			str.append(", ");
		str.append("DELETE");
	}

	return (str);
}

void	replace_all_substr(std::string &str, const std::string &ori_substr, const std::string &new_substr)
{
	if (ori_substr.empty())
		return;
	size_t	pos = 0;
	while (1)
	{
		pos = str.find(ori_substr, pos);
		if (pos == std::string::npos)
			break;
		str.replace(pos, ori_substr.size(), new_substr);
		pos += new_substr.size();
	}
}

bool	operator==(const listen_socket& lhs, int fd)
	{ return lhs.fd == fd; }

bool	operator==(int fd, const listen_socket& rhs)
	{ return fd == rhs.fd; }

std::string	str_tolower(std::string str)
{
	std::transform(str.begin(), str.end(), str.begin(), ::tolower);
	return str;
}

