#include "net.h"
#include "distlib.h"
#include "config.h"
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFSIZE 2048

int main(int argc, char **argv) {
	struct sockaddr *peername=0;
	int peernamelen=0;
	int listensock, sockids[MAX_CLIENTS];
	int i=0,x,bytes;
	int taskid;
	char buffer[BUFSIZE];
	if ((listensock=createlisten(PORT))<0) return(-1);
	fcntl(listensock, F_SETFL, O_NONBLOCK);
	while(1) {
		if ( (sockids[i]=accept(listensock, peername, &peernamelen))>0 ) {
			printf("Recieved connection\n");
			fcntl(sockids[i++], F_SETFL, O_NONBLOCK);
		}
		usleep(10000);
		for (x=0;x<i;x++) {
			if ((bytes=recv(sockids[x],buffer,sizeof(buffer)-1,0))>0) {
				printf("Recieved %i bytes.\n",bytes);
				taskid=distlib_decode(buffer, bytes);
				write(sockids[x], &taskid, sizeof(taskid));
			}
		}
	}
}
