#include "main.h"
#include "network.h"
#include "console.h"
#include "network_client.h"

int teste = 0;

void network_logic(clientState *cs) {
  // only if client is connected
  if (cs->connected) {
    client_sendall(cs);
    teste++;
    if (teste%100==0) {
      client_addPacket(&cs, PACKET_CLIENT_CHAT, "ui que coisa tao boa =)");
      if (teste >= 200) teste = 0;
    }
    client_receive(cs);
  }
}

void client_receive(clientState *cs) {
  unsigned int maxfd = 0;
  struct timeval tv;
  int result;
  fd_set active;
  packet *p;

  FD_ZERO(&active);
  if (cs->connected == TRUE) {
    FD_SET(cs->socket, &active);
    maxfd = cs->socket;
  }
  else {
    console_addline("DISCONNECTED!");
    printf("\n!!! DISCONNECTED !!!\n");
    return;
  }

  tv.tv_sec  = 0;
  tv.tv_usec = 0;
  result = select(maxfd + 1, &active, NULL, NULL, &tv);
  switch (result) {
    case -1: perror("select"); break;
    case 0: break;
    default: {
      p = packet_read(cs);
      if (p->type != PACKET_INVALID) {
        printf("received message type: %d %s\n", p->type, p->buffer);
        client_handle_packet(p);
        free(p->buffer);
        free(p);
      }
      else {
        console_addline("DISCONNECTED!");
        printf("\n!!! DISCONNECTED !!!\n");
        free(p);
      }
    }
  }
}

void client_handle_packet(packet *p) {
  switch(p->type) {
    /* login successful */
    case PACKET_LOGINOK: {
      console_addline(p->buffer);
      break;
    }
    /* another client joins wou */
    case PACKET_CLIENT_JOIN: {
      console_addline(p->buffer);
      break;
    }
    /* chat line */
    case PACKET_CLIENT_CHAT: {
      console_addline(p->buffer);
      break;
    }
  }
}
