#include "mr4th/mr4th_base.h"
#include <ncurses.h>

#include "mr4th/mr4th_base.c"

int main(){
  // initializes ncurses
  initscr();
  
  // settings
  noecho();
  cbreak();
  curs_set(0);
  
  // get size
  int window_x = 0;
  int window_y = 0;
  getmaxyx(stdscr, window_y, window_x);
  
  {
    clear();
    
    // size & corners
    move(0, 0);
    printw("SIZE: %d, %d", window_x, window_y);
    if (window_y > 2){
      mvaddch(window_y - 1, 0, '#');
      mvaddch(window_y - 1, window_x - 1, '#');
    }
    mvaddch(0, window_x - 1, '#');
    
    refresh();
  }
  
  // program
  int y_counter = 0;
  for (;;){
    int c = getch();
    
    // apply resize
    if (c == KEY_RESIZE){
      getmaxyx(stdscr, window_y, window_x);
    }
    
    clear();
    
    // size & corners
    move(0, 0);
    printw("SIZE: %d, %d", window_x, window_y);
    if (window_y > 2){
      mvaddch(window_y - 1, 0, '#');
      mvaddch(window_y - 1, window_x - 1, '#');
    }
    mvaddch(0, window_x - 1, '#');
    
    // (27 '^[' ESC)
    move(1, 0);
    if (c == 27){
      printw("ESC ");
      
      // read escape bytes
      nodelay(stdscr, 1);
      int bcount = 0;
      char b[10];
      for (;;){
        char bx = getch();
        if (bx == ERR){
          break;
        }
        if (bcount < 10){
          b[bcount] = bx;
        }
        bcount += 1;
      }
      nodelay(stdscr, 0);
      
      // print escape
      int bcount_clamped = Min(10, bcount);
      for (int i = 0; i < bcount_clamped; i += 1){
        printw("%u ", b[i]);
      }
      if (bcount_clamped < bcount){
        printw("... (%u more), ", bcount - bcount_clamped);
      }
    }
    else{
      printw("'%c' [%u]", c, c);
    }
    
    refresh();
  }
  
  // end ncurses
  endwin();
  
  return(0);
}
