#include <gear/ui/gui.h>
#include <gear/ui/console.h>
#include <log.c/log.h>

/*
    sz combined_len = console->output.len + len;

    if(combined_len > G_CONSOLE_MAX_LEN) {
        sz required_trim = combined_len - G_CONSOLE_MAX_LEN;
        if(required_trim < G_CONSOLE_MAX_LEN / 10) required_trim = G_CONSOLE_MAX_LEN / 5;
        memcpy(console->output.buf, console->output.buf + required_trim, G_CONSOLE_MAX_LEN - required_trim);
    }*/


char format_input_buf[G_CONSOLE_MAX_LEN] = { 0 };
char fmt[G_CONSOLE_MAX_LEN];

void log_callback(log_Event* event) {
    strncpy(fmt, event->fmt, G_CONSOLE_MAX_LEN);
    strcat(fmt, "\n");
    sz len = vsnprintf(format_input_buf, G_CONSOLE_MAX_LEN, fmt, event->ap);

    g_console* console = event->udata;
    while(console->output.len + len >= G_CONSOLE_BUFFER_SIZE) {
        char* new_start = memchr(console->output.buf, '\n', G_CONSOLE_MAX_LEN);
        if(new_start == NULL) {
            new_start = console->output.buf;
        }

        new_start++;

        sz len = new_start - console->output.buf;
        memmove(console->output.buf, new_start, G_CONSOLE_BUFFER_SIZE - len);
        console->output.len -= len;
    }

    strcat(console->output.buf, format_input_buf);
    console->output.len += len;
}

g_gui_layer* g_console_create() {
    g_console* console = calloc(1, sizeof(g_console));
    if(console != NULL) {
        log_info("Console allocated successfully");
        log_debug("Console pointer: %p", console);

        memset(&console->input, 0, G_CONSOLE_BUFFER_SIZE);
        memset(&console->output, 0, G_CONSOLE_BUFFER_SIZE);
    } else {
        log_fatal("Failed to allocate console");
        exit(EXIT_FAILURE);
    }

    log_add_callback(log_callback, console, LOG_INFO);

    g_gui_layer* layer = calloc(1, sizeof(g_gui_layer));
    layer->name = "Console";
    layer->draw = g_console_draw;
    layer->data = console;

    return layer;
}
