#include "base/base_inc.h"
#include "os/os_inc.h"

// TODO(allen): INCOMPLETE EXAMPLE - maybe finish this someday

// TODO(allen): define STB overrides

#define STBTT_malloc(x,u) arena_push((Arena*)(u), (x))
#define STBTT_free(x,u) ((void)(x), (void)(u))

#include "stb_ttf.h"

#include <stdio.h>

#include "base/base_inc.c"
#include "base/base_big_functions.c"
#include "os/os_inc.c"

#define STB_TRUETYPE_IMPLEMENTATION
#include "stb_ttf.h"

int
main(int argc, char **argv){
  // init
  os_main_init(argc, argv);
  
  // check args
  if (argc != 2){
    printf("usage: %s <ttf-file>\n", argv[0]);
    exit(1);
  }
  
  // get scratch
  ArenaTemp scratch = arena_get_scratch(0, 0);
  
  // load file
  char *in_file_name = argv[1];
  String8 data = os_file_read(scratch.arena, str8_cstring((U8*)in_file_name));
  if (data.size == 0){
    printf("failed to load %s\n", in_file_name);
    exit(1);
  }
  
  // parse the font
  stbtt_fontinfo info = {0};
  int font_parse_success = stbtt_InitFont(&info, data.str, 0);
  info.userdata = scratch.arena;
  
  // common font metrics
  int raw_ascent = 0;
  int raw_descent = 0;
  int raw_line_gap = 0;
  stbtt_GetFontVMetrics(&info, &raw_ascent, &raw_descent, &raw_line_gap);
  
  float scale = stbtt_ScaleForPixelHeight(&info, 20.f);
  
  // NOTE(allen): experiment:
  // I want to see what it looks like when we map codepoint -> index
  int glyph = stbtt_FindGlyphIndex(&info, 'A');
  
  // rasterize glyphs
  int glyph_count = info.numGlyphs;
  for (int i = 0; i < glyph_count; i += 1){
    RectS32 box = {0};
    stbtt_GetGlyphBitmapBox(&info, i, scale, scale,
                            &box.x0, &box.y0, &box.x1, &box.y1);
    
    V2S32 dim = dim_from_rects32(box);
    
    U8 *buf = push_array(scratch.arena, U8, dim.x*dim.y);
    stbtt_MakeGlyphBitmap(&info, buf, dim.x, dim.y, dim.x, scale, scale, i);
    
    // TODO(allen): problem:
    // it doesn't look like the library gives any way to go
    // from index -> codepoint which we would need to do a full
    // font capture.
    // if we play along with it's game we'd have to choose our
    // codepoints first, which does not work well with the task of
    // supporting arbitrary font,language combinations.
  }
  
  
  return(0);
}
