#include "../network.h"
#include "network_server.h"
#include "user.h"
#include <stdio.h>

void server_handle_packet(clientState *cs, packet *p) {
  char *login, *password, *character;
  char msg[MSG_LEN];

  memset(msg, 0, MSG_LEN);

  switch(p->type) {

    /* client sends LOGIN information */
    case PACKET_CLIENT_LOGIN: {
      login = strtok(p->buffer, "#");
      password = strtok(NULL, "#");
      character = strtok(NULL, "#");
      /* LOGIN OK */
      if (user_checklogin(login, password)) {
        // send message to all
        sprintf(msg, "%s has joined the game", character);
        sendall_except(cs, PACKET_CLIENT_JOIN, msg);
        // send message to client logging
        client_addPacket(&cs, PACKET_LOGINOK, "Logged in!");
        printf("> User login information: OK\n");
      }
      /* LOGIN NOT OK */
      else {
        client_addPacket(&cs, PACKET_LOGINERROR, "Invalid username or password!");
        printf("> User login information: NOT OK!\n");
      }
      break;
    }


    /* client sends CHAT line */
    case PACKET_CLIENT_CHAT: {
      printf("it's a chat line\n");
      sendall_except(NULL, PACKET_CLIENT_CHAT, p->buffer);
      break;
    }
  }
}

/* sends a message to all clients except <cs>
 * if cs is NULL then sends to all clients
 */
void sendall_except(clientState *cs, int type, char *msg) {
  int i;

  // temp clientState to malloc the actual i client
  clientState *temp;
  //temp = (clientState*)malloc(sizeof(struct clientState));

  printf("going to send to %i clients\n", numclients);
  for (i=0; i<numclients; i++) {
    if (cs == NULL || cs->socket != _clients[i].socket) {
      temp = &_clients[i];
      printf("added packet\n");
      client_addPacket(&temp, type, msg);
    }
  }
  printf("vou free\n");
  //free(temp);
  printf("fred!!!!\n");
}
