
#include "Webserv.hpp"

#define MAX_EVENTS 42 // arbitrary
#define TIMEOUT 3000

void	Webserv::run()
{
	std::cerr << "Server started\n";
	struct epoll_event	events[MAX_EVENTS];
	int	nfds;
	int	i;
	int	count_loop = 0;
	std::vector<listen_socket>::iterator	it_socket;

	g_run = true;
	while (g_run)
	{
		std::cerr << ++count_loop << "----loop epoll()\n";
		nfds = ::epoll_wait(_epfd, events, MAX_EVENTS, TIMEOUT);
		if (nfds == -1)
		{
			std::perror("err epoll_wait()");
			throw std::runtime_error("Epoll wait");
		}
		else if (nfds == 0)
		{
			if (!_clients.empty())
			{
				std::cerr << "Timeout " << TIMEOUT << "ms\n";
				_close_all_clients();
			}
		}
		i = 0;
		while (i < nfds)
		{
			// TODO : handle EPOLLERR and EPOLLHUP
			it_socket = std::find(_listen_sockets.begin(), _listen_sockets.end(), events[i].data.fd);
			if (it_socket != _listen_sockets.end() && events[i].events & EPOLLIN)
				_accept_connection(*it_socket);
			else if (events[i].events & EPOLLIN)
				_request( &(*std::find(_clients.begin(), _clients.end(), events[i].data.fd)) );
			else if (events[i].events & EPOLLOUT)
				_response( &(*std::find(_clients.begin(), _clients.end(), events[i].data.fd)) );
			++i;
			if (!g_run)
				break;
		}
	}
}
