
#include "Webserv.hpp"

void	Webserv::_accept_connection(listen_socket &lsocket)
{
	struct sockaddr_in					addr;
	socklen_t 							addr_len;
	int									accepted_fd;
	std::map<std::string, std::string>	infos;

	std::cerr << "accept()\n";
	addr_len = sizeof addr;
	accepted_fd = ::accept(lsocket.fd, (sockaddr*)&addr, &addr_len);
	if (accepted_fd == -1)
	{
		std::perror("err accept()");
		if (g_last_signal)
			_handle_last_signal();
		return ;
	}
	::fcntl(accepted_fd, F_SETFL, O_NONBLOCK);

	infos = _extract_infos(addr);
	Client	client(accepted_fd, &lsocket, infos["port"], infos["ip"]);
	_clients.push_back(client);
	_epoll_update(accepted_fd, EPOLLIN, EPOLL_CTL_ADD);
}

std::map<std::string, std::string>
	Webserv::_extract_infos(struct sockaddr_in addr)
{
	struct in_addr						ip_conversion;
	std::map<std::string, std::string>	infos;

	infos["port"] = ::itos( addr.sin_port );
	ip_conversion.s_addr = addr.sin_addr.s_addr;
	infos["ip"] = inet_ntoa( ip_conversion );

	return infos;
}

