#include "ServerSocket.h"

/*! \fn createSocket ()
 *  \author Stephane EKOKO <selobe@gmail.com>
 *  \version 0.1
 *  \date mardi 16 novembre 2010, 14:36:16 (UTC+0100)
 *
 *	\param int domain
 *	\param int type
 *	\param int protocol
 *
 *  \brief 
 *  \return Socket
 */

Socket createSocket(int domain, int type, int protocol) {
	Socket theReturn = socket(domain, type, protocol);
	if (theReturn == INVALID_SOCKET) {
		perror("socket()");
		exit(errno);
	}
	return theReturn;
}

/*! \fn createSocketInterface (uint32_t hostlong ,int domain ,int port ,void)
 *  \author Stephane EKOKO <selobe@gmail.com>
 *  \version 0.1
 *  \date mardi 16 novembre 2010, 15:13:27 (UTC+0100)
 *
 *
 *  \brief retourne l'interface du socket
 *  \return SocketaddrIn
 *  \param uint32_t hostlong
 *  \param int domain
 *  \param int port
 */

SockaddrInd createSocketInterface(u_int32_t h, int domain, int port) {
	SockaddrInd theReturn = { 0 };
	theReturn.sin_addr.s_addr = htonl(h);
	theReturn.sin_family = domain;
	theReturn.sin_port = htons(port);
	return theReturn;
}

int main(int argc, char * argv[]) {
	TheHost * h;
	SockaddrInd ac;
	FILE *theIn, *theOut;
	char reponse1[200];
	Socket theConnection, theConversation;
	// Gets Computer Hostname

	h = gethostbyname("localhost");
	if (h == NULL) {
		perror("gethostbyname()");
		exit(errno);
	}

	theConnection = createSocket(AF_INET, SOCK_STREAM, 0);
	SockaddrInd as = createSocketInterface(INADDR_ANY, AF_INET, 5003);

	if (bind(theConnection, (struct sockaddr *) &as, sizeof(SockaddrInd)) == SOCKET_ERROR) {
		perror("bind()");
		exit(errno);
	}

	if (listen(theConnection, 3) == SOCKET_ERROR) {
		perror("listen()");
		exit(errno);
	}
	while (1) {

		int longueur = sizeof(SockaddrInd);
		printf("toto\n");
		printf("nono\n");
		theConversation = accept(theConnection, (struct sockaddr *) &ac, &longueur);
		theIn = fdopen(theConversation, "r");
		theOut = fdopen(theConversation, "w");
		if(theIn==NULL || theOut==NULL){
			perror("fdopen()");
			exit(errno);
		}
		while(fgets(reponse1, 100, theIn)!=NULL){
			printf("%s\n",reponse1);
		}

	}

	return (EXIT_SUCCESS);
}

