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

struct nk_font* g_gui_font;

g_gui* g_gui_create() {
    snk_setup(&(snk_desc_t){
        .dpi_scale = sapp_dpi_scale(),
        .logger.func = slog_func,
    });
    log_info("Sokol nuklear initialized successfully");

    g_gui* gui = calloc(1, sizeof(g_gui));
    if(gui != NULL) {
        log_info("GUI allocated successfully");
        log_debug("GUI pointer: %p", gui);

        g_gui_add_layer(&gui->layers, g_console_create, g_console_destroy);
    } else {
        log_fatal("Failed to allocate GUI");
        exit(EXIT_FAILURE);
    }

    struct nk_font_atlas* atlas = calloc(1, sizeof(struct nk_font_atlas));
    if(atlas != NULL) {
        log_info("Font atlas allocated successfully");
        log_debug("Font atlas pointer: %p", atlas);

        nk_font_atlas_init_default(atlas);
        nk_font_atlas_begin(atlas);

        f32 font_size = 22.05f;
        struct nk_font_config config = nk_font_config(font_size);
        config.pixel_snap = true;

        g_gui_font = nk_font_atlas_add_from_memory(atlas,
                res_OpenSans_Regular_ttf,
                res_OpenSans_Regular_ttf_len,
                font_size, &config);

        i32 atlas_width, atlas_height;
        const u8* pixels = nk_font_atlas_bake(atlas, &atlas_width, &atlas_height, NK_FONT_ATLAS_RGBA32);

        sg_image font_image = sg_make_image(&(sg_image_desc){
            .label = "Font image",
            .width = atlas_width,
            .height = atlas_height,
            .data.subimage[0][0] = (sg_range){
                .ptr = pixels, 
                .size = atlas_width * atlas_height * 4
            },
            .pixel_format = SG_PIXELFORMAT_RGBA8
        });

        sg_sampler font_sampler = sg_make_sampler(&(sg_sampler_desc){
            .label = "Font sampler"
        });

        snk_image_t snk_img = snk_make_image(&(snk_image_desc_t){
            .image = font_image,
            .sampler = font_sampler
        });

        nk_font_atlas_end(atlas, snk_nkhandle(snk_img), NULL);
    } else {
        log_fatal("Failed to allocate font atlas");
        exit(EXIT_FAILURE);
    }

    return gui;
}
