#include <ncurses.h>
#include <iostream>
#include <csignal>
#include <cstdlib>
#include <time.h>

#include "board.h"
#include "networking.h"
#include "util.h"

connection *c;

// Stop the terminal from freaking out when the program is exited
// Even if other stuff isn't cleaned up, the terminal will
// still be useable
void cleanup_screen(int signum) {
  destroy_screen();
  
  delete c;
  
  exit(signum);
}

int main(int argc, char *argv[]) {
  srand(time(NULL));
  
  init_screen();
  
  signal(SIGINT, cleanup_screen);
  signal(SIGTERM, cleanup_screen);
  signal(SIGSEGV, cleanup_screen);
  
  mvprintw(0, 0, "Client or server?");
  mvprintw(1, 0, "1) Server");
  mvprintw(2, 0, "2) Client");
  
  int key = getch();
  while (!(key == '1' || key == '2')) key = getch();
    
  if (key == '1') {
    c = new server_connection;
  } else {
    c = new client_connection;
  }
  
  board player_board(PLAYER);
  std::string opponent_board_desc = c->exchange_message(player_board.get_description());
  board opponent_board(OPPONENT, opponent_board_desc);
  
  clear();
  player_board.draw();
  opponent_board.draw();
  
  while(true) {
    clear_message();
    display_message_1("Select Target Position");
    display_message_2("Press Space To Fire");
    std::string move = opponent_board.get_move();
    clear_message();
    display_message_1("Waiting for Opponent");
    refresh();
    std::string opponent_move = c->exchange_message(move);
    
    clear_message();
    
    player_board.make_move(opponent_move);
    opponent_board.make_move(move);
    
    player_board.draw();
    opponent_board.draw();
    
    if (player_board.has_lost() || opponent_board.has_lost()) break;
    
    usleep(1000000);
  }
  
  clear_message();
  if (player_board.has_lost() && !opponent_board.has_lost()) {
    display_message_1("You Lose.");
    display_message_2("Better luck next time.");
  } else if (!player_board.has_lost() && opponent_board.has_lost()) {
    display_message_1("You Win!");
    display_message_2("Congratulations!");
  } else {
    display_message_1("It's a tie!");
    display_message_2("What are the odds?!?");
  }
  
  player_board.draw_game_over();
  opponent_board.draw_game_over();
  
  getch();
  
  destroy_screen();
  delete c;
}