/* 
    TowBowlTactics: Strategy game for X11

    Copyright (C) 2002 Pascal Bourut (toweld@rocketmail.com)

    Network part from grrrreg (greg@doodoo.darktech.org)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "NetServer.h"

NetServer::NetServer() {
  SDLNet_Init();
  port = NET_DEFAULT_PORT;
  type = SERVER;
  client_connected = false;
  opened = false;
}

NetServer::NetServer(Uint16 le_port) {
  SDLNet_Init();
  port = le_port;
  type = SERVER;
  client_connected = false;
  opened = false;
}

NetServer::~NetServer() {
  SDLNet_Quit();

}

bool NetServer::is_client_connected() {
  return client_connected;
}

int NetServer::open(Uint16 le_port) {
  // Ouvre et attend la connexion d'un client !
  port = le_port;
  if(SDLNet_ResolveHost(&serverIP,NULL,port)==-1) {
    printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
    return(0);
  }

  socketSet = SDLNet_AllocSocketSet(NET_NB_SOCKETS);

  serverSocket = SDLNet_TCP_Open(&serverIP); // DANS UN IF PLEASE

  if (!serverSocket) {
    printf("NetServer::open(port): %s\n", SDLNet_GetError());
    return 0;
  }

  SDLNet_TCP_AddSocket(socketSet, serverSocket);

  return(1);
}


int NetServer::open() {
  // Ouvre et attend la connexion d'un client !
  port = NET_DEFAULT_PORT;
  if(SDLNet_ResolveHost(&serverIP,NULL,port)==-1) {
    printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
    return(0);
  }

  socketSet = SDLNet_AllocSocketSet(NET_NB_SOCKETS);

  serverSocket = SDLNet_TCP_Open(&serverIP); 
 
  if (!serverSocket) {
  printf("NetServer::open(): %s\n", SDLNet_GetError());
  return 0;
  }
  
  SDLNet_TCP_AddSocket(socketSet, serverSocket);

  opened = true;

  return(1);
}

bool NetServer::is_opened(){
	return opened;
}

int NetServer::wait_client() {
	port = NET_DEFAULT_PORT;
	SDLNet_CheckSockets(socketSet, WAIT_TIMEOUT);

	if (SDLNet_SocketReady(serverSocket) ) {
   
		parloteSocket=SDLNet_TCP_Accept(serverSocket);
		if(!parloteSocket) {
			printf("NetServer::open(): %s\n", SDLNet_GetError());
			client_connected = false;
			return(0);
		}
   
		SDLNet_TCP_AddSocket(socketSet, parloteSocket);
 
		client_connected = true;
		return(1);
	}
	client_connected = false;
	return (0);
}
