#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#include "serverobject.h"
#include "serverconfig.h"
#include "netconfig.h"
#include "servergame.h"
#include "serverdata.h"
#include "mainplayerthread.h"
#include "readnetworkdata.h"
#include "thread.h"
#include "collision.h"


pthread_t ServerThreads[MAX_PLAYERS+1];
ConnectionStruct Connections[MAX_PLAYERS];
int GamePort;
int listenfd;
int StopServer;


void *Server(void *threadid)
{
  int rc, i;
  struct sockaddr_in servaddr;
  struct timeval timeout;

  for (i=0; i<MAX_PLAYERS; i++) {
    Connections[i].Connected=0;
  }
  NumConnectedPlayers=0;
  StopServer=0;

  if (!threadid) {
    ReadServerConfig(ServerSingleConfigFileName);
  }

  if ((listenfd=socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    printf("socket error\n");
    exit(3);
  }

  // Set a timeout of 5 seconds for listening
  timeout.tv_sec=5;
  timeout.tv_usec=0;
  setsockopt(listenfd, SOL_SOCKET, SO_RCVTIMEO,
	     &timeout, sizeof(struct timeval));

  memset(&servaddr, 0, sizeof(servaddr));
  servaddr.sin_family=AF_INET;
  servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
  servaddr.sin_port=htons(GamePort);

  InitCollisionFunctions();

  if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
    printf("bind error\n");
    exit(4);
  }

  // Spawn off the main game thread
  if (rc = pthread_create(&ServerThreads[MAX_PLAYERS], NULL,
			  StartGame, (void *)MAX_PLAYERS)) {
    printf("ERROR, return code from pthread_create() is %d\n", rc);
    exit(6);
  }

  usleep(100000);

  ReadNetworkData();

  exit(7);
}
