/*
 * An example of server implementation
 * by Hoang Nguyen
 * Feel free to modify and copy the code
 * and use it AT YOUR OWN RISK
*/


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>


#include <pthread.h>

#include "msg.h"

void *socketThread(void* data) {
	int numbytes;

	int sockfd = *((int *) data);

	free((int *) data);

	printf("\tStart a thread to server this client\n");
	
	msg_t msg, reply;

	while (1) {
		recvMessage(sockfd, &msg);
	
		if (msg.len > 0) {	
			
			msg.data[msg.len] = 0;

			printf("Received message %s\n", msg.data);

			sprintf(reply.data, "I am available");
			reply.len = strlen(reply.data);

			printf("\tReply %s\n", reply.data);

			sendMessage(sockfd, &reply);
		}
	}
	close(sockfd);

}

void serveClient(int sockfd) {
	pthread_t tid;


	int* psockfd = (int *) malloc(sizeof(int));
	*psockfd = sockfd;

	int ret = pthread_create(&tid, NULL, socketThread, (void *) psockfd);
}

int main(int argc, char* argv[]) {
	
	if (argc == 1) {
		printf("server port\n");
		return 0;
	}
	
	startServer(argv[1], (void *)(serveClient));
	
	return 0;
}