#include <Flanterm/src/flanterm.h>
#include <Flanterm/src/flanterm_backends/fb.h>
#include <device/device.h>
#include <device/terminal.h>
#include <libk/std.h>
#include <limine/requests.h>
#include <mm/liballoc.h>
#include <proc/capability.h>
#include <proc/proc.h>
#include <status.h>
#include <sys/debug.h>

struct flanterm_context* ft_ctx;

void* ft_malloc (size_t n) { return malloc (n); }

void ft_free (void* ptr, size_t size) {
  (void)size;
  free (ptr);
}

bool terminal_init (struct device* device, void* arg) {
  (void)arg, (void)device;

  struct limine_framebuffer_response* fb_r = limine_framebuffer_request.response;
  struct limine_framebuffer* fb = fb_r->framebuffers[0];

  ft_ctx = flanterm_fb_init (&ft_malloc, &ft_free, fb->address, fb->width, fb->height, fb->pitch,
                             fb->red_mask_size, fb->red_mask_shift, fb->green_mask_size,
                             fb->green_mask_shift, fb->blue_mask_size, fb->blue_mask_shift, NULL,
                             NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 1, 0, 0, 0, 0);

  return true;
}

void terminal_fini (struct device* device) { (void)device; }

int terminal_putstr (struct device* device, struct proc* proc, struct reschedule_ctx* rctx,
                     void* a1, void* a2, void* a3, void* a4) {
  (void)a2, (void)a3, (void)a4, (void)device, (void)rctx;

  if (!(proc->procgroup->capabilities & PROC_CAP_TERMINAL))
    return -ST_PERMISSION_ERROR;

  char* string = (char*)a1;
  size_t* len = (size_t*)a2;

  if (string == NULL || len == NULL)
    return -ST_BAD_ADDRESS_SPACE;

  flanterm_write (ft_ctx, string, *len);

  return ST_OK;
}

int terminal_dimensions (struct device* device, struct proc* proc, struct reschedule_ctx* rctx,
                         void* a1, void* a2, void* a3, void* a4) {
  (void)proc, (void)rctx, (void)a3, (void)a4, (void)device;

  if (a1 == NULL || a2 == NULL)
    return -ST_BAD_ADDRESS_SPACE;

  flanterm_get_dimensions (ft_ctx, (size_t*)a1, (size_t*)a2);

  return ST_OK;
}
