


#include "ConfigParser.hpp"

void	ConfigParser::_post_processing(std::vector<ServerConfig> *servers)
{
	std::vector<ServerConfig>::iterator	it = servers->begin();

	while (it != servers->end())
	{
		// host and port are Mandatory
		if (it->host == "")
			throw std::invalid_argument("Config file needs a host and port");

		// root is mandatory
		if (it->root == "")
			throw std::invalid_argument("Config file needs a root");

		// index is mandatory in Server
		if (it->index.empty())
			throw std::invalid_argument("Config file needs an Index");

		if (it->client_body_limit == 0)
			it->client_body_limit = 5000;	// what is the recomended size?
		

		// if error_pages is left empty, we'll use the defaults which
			// i believe are set elsewhere...


		if (!_find_root_path_location(it->locations))
		{
			LocationConfig	tmp;

			tmp.path = "/";
			tmp.root = it->root;
			tmp.index = it->index;
			tmp.allow_methods = ANY_METHODS;
			tmp.autoindex = false;
			tmp.redirect_status = 0;
			it->locations.push_back(tmp);
		}

		std::vector<LocationConfig>::iterator	it_l = it->locations.begin();

		while (it_l != it->locations.end())
		{
			if (it_l->root == "")
				it_l->root = it->root;

			if (it_l->allow_methods == UNKNOWN)
				it_l->allow_methods = ANY_METHODS;

// also 
			if (it_l->index.empty() && it_l->autoindex == false)
				it_l->index = it->index;

	// nothing to be done for cgi_ext, error_pages, redirect

			if (path_is_valid(it_l->root + it_l->path) == 1 \
				&& it_l->path[it_l->path.size() - 1] != '/')
				it_l->path.push_back('/');

			++it_l;
		}
		std::sort(it->locations.begin(), it->locations.end());
		std::reverse(it->locations.begin(), it->locations.end());

		++it;
	}
}

bool	ConfigParser::_find_root_path_location(std::vector<LocationConfig> locations)
{
	std::vector<LocationConfig>::iterator it = locations.begin();

	while (it != locations.end())
	{
		if (it->path.compare("/") == 0)
		{
	//		std::cout << "in compare: " << it->path << "  --  ";
			return true;
		}
		++it;
	}
	return false;
}

