#include "mr4th/mr4th_base.h"
#include "mr4th/mr4th_stdio.h"
#include "mr4th/mr4th_prng.h"
#include "mr4th/mr4th_ncurses.h"

#include "mr4th/mr4th_base.c"
#include "mr4th/mr4th_stdio.c"
#include "mr4th/mr4th_prng.c"
#include "mr4th/mr4th_ncurses.c"

int main(){
  ArenaTemp scratch = arena_get_scratch(0, 0);
  
  // prng
  PRNG prng = {0};
  {
    PRNG_Seed seed;
    os_get_entropy(&seed, sizeof(seed));
    prng = prng_from_seed(&seed);
  }
  
  // initialize ncurses
  initscr();
  
  if (!has_colors()){
    goto no_color;
  }
  start_color();
  
  noecho();
  cbreak();
  curs_set(0);
  
  // initialize ncurses colors
  {
#define X(F,B) init_pair(NCRS_ColorPair_##F##_##B, COLOR_##F, COLOR_##B);
    NCRS_ColorPair_XList(X)
#undef X
  }
  
  // virtual buffer
  NCRS_Bfr bfr = ncrs_bfr_alloc(scratch.arena, 160, 40);
  
  // background decorations
  static U8 chr_array[] = {
    '#', '%', '+', '~',
    '*', '|', '-', '$',
    '<', '\\', '/', '>',
    ',', ',', '.', '.',
    ' ', ' ', ' ', ' ',
    ' ', ' ', ' ', ' ',
    ' ', ' ', ' ', ' ',
    ' ', ' ', ' ', ' ',
    ' ', ' ', ' ', ' ',
    ' ', ' ', ' ', ' ',
  };
  
  static U8 color_array[] = {
    NCRS_ColorPair_RED_BLACK, NCRS_ColorPair_GREEN_BLACK, NCRS_ColorPair_BLUE_BLACK,
    NCRS_ColorPair_YELLOW_BLACK, NCRS_ColorPair_MAGENTA_BLACK, NCRS_ColorPair_CYAN_BLACK,
  };
  
  // program
  for (;;){
    // render to bfr
    ncrs_bfr_fill_rect(&bfr, (RectS32){0, 0, 160, 40}, ' ', 0);
    ncrs_bfr_outline_rect(&bfr, (RectS32){0, 0, 160, 40},
                          '#', NCRS_ColorPair_WHITE_BLACK);
    
    ncrs_bfr_clip(&bfr, (RectS32){1, 1, 159, 39});
    for (S32 iy = 0; iy < bfr.h; iy += 1){
      for (S32 ix = 0; ix < bfr.w; ix += 1){
        U8 chr = chr_array[prng_u32_bounded(&prng, ArrayCount(chr_array))];
        U8 color = color_array[prng_u32_bounded(&prng, ArrayCount(color_array))];
        ncrs_bfr_point(&bfr, ix, iy, chr, color);
      }
    }
    ncrs_bfr_clip_clear(&bfr);
    
    ncrs_bfr_fill_rect(&bfr,    (RectS32){58, 8, 88, 19}, ' ', NCRS_ColorPair_WHITE_BLACK);
    ncrs_bfr_outline_rect(&bfr, (RectS32){58, 8, 88, 19}, '#', NCRS_ColorPair_WHITE_BLACK);
    ncrs_bfr_write(&bfr, 60, 10, str8_lit("Continue"), NCRS_ColorPair_BLACK_WHITE);
    ncrs_bfr_write(&bfr, 60, 12, str8_lit("New Game (Abandon Current)"), NCRS_ColorPair_WHITE_BLACK);
    ncrs_bfr_write(&bfr, 60, 14, str8_lit("Journal"), NCRS_ColorPair_WHITE_BLACK);
    ncrs_bfr_write(&bfr, 60, 16, str8_lit("Quit"), NCRS_ColorPair_WHITE_BLACK);
    
    // bfr -> screen
    ncrs_bfr_to_window(&bfr, stdscr);
    
    int c = getch();
  }
  
  // end ncurses
  endwin();
  
  if (0){ no_color:
    endwin();
    printf("no ncurses color support\n");
  }
  
  arena_release_scratch(&scratch);
  return(0);
}
