//troy Rosin

#include <SDL2/SDL_net.h>
#include <SDL2/SDL.h>
#include <string.h>
#include <stdio.h>
#include <mydebug.h>
#include <net.h>

#define MAX_SOCKS 4

char buff[PACKSZ];
char pack[PACKSZ], pack2[PACKSZ];

void game_server()
{
  IPaddress *ip, _ip, *cip;
  TCPsocket sock, csock;
  TCPsocket sock_arr[MAX_SOCKS];
  ip = &_ip;
  SDLNet_SocketSet socks;
  int i;

  Uint16 c_port;
  Uint32 c_ip;
  
  int flag = 1;
  int ret = 0;

  SDL_Init(0);

  SDLNet_Init();
 
  if(SDLNet_ResolveHost(ip, NULL, PORT) == -1)
  {
    printf("SDLNet_resolvehost error: %s\n", SDLNet_GetError());
    exit(1);
  }  

  sock = SDLNet_TCP_Open(ip);
  if(!sock)
  {
    printf("SDL_Net_TCP_Open error: %s\n", SDLNet_GetError());
    exit(1);
  }
 
  socks = SDLNet_AllocSocketSet(MAX_SOCKS);
  
  for(i = 0; i < MAX_SOCKS; ++i)
  {
    sock_arr[i] = NULL;
  }
  
  while(flag)
  {
    csock = SDLNet_TCP_Accept(sock);
    if(!csock && SDLNet_CheckSockets(socks, 0) > 0 ){
      //no new connection and there is updates on socks
      for(i = 0; i < MAX_SOCKS; ++i)
      {//check each sock for data and handle it
        csock = sock_arr[i];
        if(csock == NULL){continue;}
        if(SDLNet_SocketReady(csock)){
          ret = SDLNet_TCP_Recv(csock, pack, PACKSZ);
          if(ret < PACKSZ){
            printf("TCP recv error: %s\n", SDLNet_GetError());
            sock_arr[i] = NULL;
            SDLNet_TCP_DelSocket(socks, csock);
            SDLNet_TCP_Close(csock);
            continue;
          }
          read_to_buff((Uint32*)buff, (Uint32*)pack, PACKSZ);
          switch(((packet*)buff)->type)
          {
            case G_STATE:
              PRINT_M("got to get state case");
              break;
            case S_STATE:
              PRINT_M("got to set state case");
              break;
            case HOSTS_REQ:
              PRINT_M("got to hosts request state");
              break;
            case NEW_HOST:
              PRINT_M("got to new host state");
              break;
            case JOIN_REQ:
              PRINT_M("got to join request state");
              break;
            case U_NAME:
              PRINT_M("got to update name state");
              flag = 0;
              break;
          }
        }
      }      
    }
    else if (csock) {
      cip = SDLNet_TCP_GetPeerAddress(csock);
      if(!cip){
          printf("get peer addr error: %s\n", SDLNet_GetError());
      }
      else {
        PRINT_M("we got a new connection!");
        if(SDLNet_TCP_AddSocket(socks, csock) <= 0){
          printf("add sock to set error: %s\n", SDLNet_GetError());
        } 
        for(i = 0; i < MAX_SOCKS; ++i){
          if(sock_arr[i] == NULL){ sock_arr[i] = csock; break; }
        }
      }
    }
    return;
  }

  SDLNet_TCP_Close(sock);
  SDLNet_Quit();
  SDL_Quit();

}


int main(void)
{
    game_server(); 
    puts("donzo");
  return 0;
}




