//Main SERVER
#include <iostream>

#include "../libnetwork/psocket_init.h"
#include "../definition_ports.h"

#define BACKLOG 10

int main(int argc, char **argv) {
	std::cout << "Hello, world server!" << std::endl;
	int sockfd = createTCPsocketServer(PORT, BACKLOG);
	int new_fd;
	socklen_t sin_size;
	struct sockaddr_storage their_addr; // connector's address information
	char s[INET6_ADDRSTRLEN];
	char buffer[MAXDATASIZE];
	printf("server: waiting for connections...\n");
	bool run(true), waitForPacket;
	while(run){
		/* This check the sd if there is a pending connection.
		* If there is one, accept that, and open a new socket for communicating */
		sin_size = sizeof their_addr;
		new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
		if(new_fd != - 1){  //si on peut encore se connecter
			close(sockfd);
			waitForPacket = true;
			while(waitForPacket){
				if (recv(new_fd, buffer, MAXDATASIZE, 0) > 0){
					printf("Client say: %s\n", buffer);
					if(strcmp(buffer, "exit") == 0){	/* Terminate this connection */
						waitForPacket = false;
						printf("Terminate connection\n");
					}
					if(strcmp(buffer, "quit") == 0){	/* Quit the program */
						waitForPacket = false;
						run = false;
						printf("Quit program\n");
					}
				}
			}
			/* Close the client socket */
			close(new_fd);
		}
	}
	close(sockfd);
	
	
	std::cout << "Arrêtage du server..." << std::endl;
	return 0;
}



