#include "flanterm.h"
#include "flanterm_backends/fb.h"
#include "spinlock/spinlock.h"
#include "bootinfo/bootinfo.h"
#include "term.h"
#include "putchar.h"
#include "fm-t-437.f16.h"

Term TERM;

void term_doinit(void *addr) {
  TERM.ftctx = flanterm_fb_init(
    NULL, // malloc
    NULL, // free
    addr, // fb addr
    BOOT_INFO.fb->width,
    BOOT_INFO.fb->height,
    BOOT_INFO.fb->pitch,
    BOOT_INFO.fb->red_mask_size,
    BOOT_INFO.fb->red_mask_shift,
    BOOT_INFO.fb->green_mask_size,
    BOOT_INFO.fb->green_mask_shift,
    BOOT_INFO.fb->blue_mask_size,
    BOOT_INFO.fb->blue_mask_shift,
    NULL, // canvas
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    FM_T_437_F16,
    8,
    16,
    0,
    0,
    0,
    20
  );
}

void term_init(void *addr) {
  term_doinit(addr);
  spinlock_init(&TERM.spinlock);
}

void term_write_unsafe(const char *s, size_t len) {
  flanterm_write(TERM.ftctx, s, len);
}

#if PUTCHAR_ == PUTCHAR_FB
  // For printf library
  void putchar_(char c) {
    term_write_unsafe(&c, 1);
  }
#endif
