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

c_line *console;
char input[MAX_LENGTH];
int caret;
int total_lines;
BITMAP *consoleBMP;
int typing = FALSE;
char prompt[10];
char *say_prompt = "Say: ";

void console_init() {
  memset(&input, 0, strlen(input));
  consoleBMP = create_bitmap(185, 600);
  caret = 0;
  total_lines = 0;
}

void console_keypress(int key) {
  int scancode = key >> 8;

  /* start and stop typing */
  if (scancode == KEY_ENTER) {
    // submit input
    if (typing) {
      console_addline(input);
      memset(&input, 0, strlen(input));
      caret = 0;
      typing = FALSE;
    }
    // start input
    else {
      strcpy(prompt, say_prompt);
      sprintf(input, prompt);
      caret += strlen(prompt);
      typing = TRUE;
    }
  }
  // add key to input
  else if (typing)
    input_addchar(key);
}

void render_console(BITMAP *bmp) {
  int i;
  int line;
  char cutinput[MAX_LENGTH];
  c_line *curr;

  // lines already in console
  line = 0;
  curr = console;
  while (curr && line<18) {
    textprintf_ex(bmp, font, 24, 445-((text_height(font)+2)*(line+1)), makecol(35,35,70), -1,"%s", curr->text);
    line++;
    curr = curr->next;
  }

  // input text line
  strcpy(cutinput, input);
  for (i=0; text_length(font, (cutinput+i))>600; i++);
  textprintf_ex(bmp, font, 24, 445, makecol(35,35,70), -1,"%s", (cutinput+i));

  // input caret
  if (typing) {
    vline(bmp, 25+text_length(font, (cutinput+i)), 444, 451, makecol(130,130,70));
  }
}

void print_console() {
  c_line *curr;
  curr = console;
  printf("LINES: \n");
  while(curr) {
    printf("%s\n", curr->text);
    curr = curr->next;
  }
}

void console_addline(char *line) {
  c_line *newline;
  c_line *curr, *next;

  newline = (c_line*)malloc(sizeof(c_line));
  newline->text = (char*)malloc(strlen(line+strlen(prompt)));
  strcpy(newline->text, (line+strlen(prompt)));
  newline->next = console;
  console = newline;
  total_lines++;

  // remove last if we have limit
  if (total_lines >= MAX_LINES) {
    curr = console;
    while (curr) {
      next = curr->next;
      if (next->next == NULL) {
        curr->next = NULL;
        free(next);
        break;
      }
      curr = curr->next;
    }
  }

  // send chat to network
  client_addPacket(&client, T_CL_CHAT, (line+strlen(prompt)));
  client_sendall(&client);
}

void input_addchar(int key) {
  int ascii, scancode;
  ascii = key & 0xff;
  scancode = key >> 8;

  // delete character from input
  if (scancode == KEY_BACKSPACE) {
    if ((caret) > (int)strlen(prompt)) {
      caret--;
      input[caret] = 0;
    }
  }
  else {
    if (caret < MAX_LENGTH-1) {
      // add character to input
      input[caret] = ascii;
      caret++;
    }
    else {
      input[caret] = '\0';
    }
  }
}
