#include "util.h"

void init_screen() {
  // Initialize ncurses screen
  initscr();
  start_color();
  
  init_pair(TEXT_WHITE, COLOR_WHITE, COLOR_BLACK);
  init_pair(TEXT_GREEN, COLOR_GREEN, COLOR_BLACK);
  init_pair(TEXT_RED, COLOR_RED, COLOR_BLACK);

  init_pair(BG_RED, COLOR_BLACK, COLOR_RED);
  init_pair(BG_BLUE, COLOR_BLACK, COLOR_BLUE);
  init_pair(BG_GREEN, COLOR_BLACK, COLOR_GREEN);
  init_pair(BG_BLACK, COLOR_BLACK, COLOR_BLACK);
  init_pair(BG_WHITE, COLOR_BLACK, COLOR_WHITE);
  init_pair(BG_CYAN, COLOR_BLACK, COLOR_CYAN);
  
  set_escdelay(0);
  enable_raw_input();
  
  nonl();
  intrflush(stdscr, FALSE);
  
  // Make it so keypad characters do what we expect
  keypad(stdscr, TRUE);
  
  // Clear the screen
  clear();
}

void destroy_screen() {
  endwin();
}

void enable_raw_input() {
  // Unbuffered input
  cbreak();
  
  // Don't echo back characters that are typed
  noecho();
  
  // Hide the cursor
  curs_set(0);
}

void enable_string_input() {
  // Buffer input
  nocbreak();
  
  // Auto echo characters back to terminal
  echo();
  
  // Show the cursor
  curs_set(1);
}

std::string getstring() {
  enable_string_input();
  
  std::string input;
  int ch = getch();
  while (ch != '\n') {
    input.push_back(ch);
    ch = getch();
  }
  
  enable_raw_input();
  
  return input;
}

int randrange(int min, int max) {
  int range = max - min + 1;
  return (rand() % range) + min;
}

int sign(int x) {
  if (x > 0) return 1;
  if (x < 0) return -1;
  return 0;
}