/*
 * Copyright (c) 2026, Chloe M.
 * Provided under the BSD-3 clause.
 *
 * Description: Boot video driver
 * Author:      Chloe M.
 */

#include <drivers/bootvid/fbio.h>
#include <ex/trace.h>
#include <ke/bpal.h>
#include "flanterm.h"
#include "flanterm_backends/fb.h"

/* Bootcons attributes */
#define DEFAULT_BG 0x000000
#define DEFAULT_FG 0xFFB000

#define DTRACE(Fmt, ...) \
    TRACE("[ BOOTVID ]: " Fmt, ##__VA_ARGS__)

static BPAL_FRAMEBUFFER Framebuffer;
static struct flanterm_context *FtCtx = NULL;
static BOOLEAN BootConsEnabled = false;
static BOOTCONS_ATTR DefaultConsAttr = {
    .Foreground = DEFAULT_FG,
    .Background = DEFAULT_BG
};

VOID
BootVidInit(VOID)
{
    BPAL_HANDLE Handle;

    KeBpalGetHandle(&Handle);
    Framebuffer = Handle.Framebuffer;

    DTRACE("framebuffer width  : %d px\n", Framebuffer.Width);
    DTRACE("framebuffer height : %d px\n", Framebuffer.Height);
}

VOID
BootVidInitCons(BOOTCONS_ATTR *Attr)
{
    if (BootConsEnabled) {
        BootVidDeInitCons();
    }

    if (Attr == NULL) {
        Attr = &DefaultConsAttr;
    }

    FtCtx = flanterm_fb_init(
        NULL,
        NULL,
        Framebuffer.Address,
        Framebuffer.Width,
        Framebuffer.Height,
        Framebuffer.Pitch,
        Framebuffer.RedMaskSize,
        Framebuffer.RedMaskShift,
        Framebuffer.GreenMaskSize,
        Framebuffer.GreenMaskShift,
        Framebuffer.BlueMaskSize,
        Framebuffer.BlueMaskShift,
        NULL,
        NULL,
        NULL,
        &Attr->Background,
        &Attr->Foreground,
        NULL,
        NULL,
        NULL,
        0, 0, 0,
        0, 0, 0, 0
    );

    BootConsEnabled = true;
    DTRACE("bootcons enabled\n");
}

VOID
BootVidConsWrite(const CHAR *String, USIZE Length)
{
    if (String == NULL || Length == 0) {
        return;
    }

    if (!BootConsEnabled) {
        return;
    }

    flanterm_write(FtCtx, String, Length);
}

VOID
BootVidDeInitCons(VOID)
{
    if (!BootConsEnabled) {
        return;
    }

    flanterm_deinit(FtCtx, NULL);
    FtCtx = NULL;
    BootConsEnabled = false;
}

BOOLEAN
BootVidConsEn(VOID)
{
    return BootConsEnabled;
}
