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

void log_callback(log_Event* event) {
    char* formatted_input;
    vasprintf(&formatted_input, event->fmt, event->ap);

    char* formatted;
    sz len = asprintf(&formatted, "%s\n", formatted_input);

    free(formatted_input);

    g_console* console = event->udata;

    for(sz i = 0; i < len; i++) {
        sl_vec_push(console->output, formatted[i]);
    }

    free(formatted);
}

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);

        console->input = (sl_string){
            .data = malloc(1),
            .size = 0,
            .capacity = 1
        };

        console->output = (sl_string){
            .data = malloc(1),
            .size = 0,
            .capacity = 1
        };
    } 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;
}
