#include <gear/graphics/textures.h>
#include <gear/images.h>
#include <log.c/log.h>

g_texture* g_texture_create(g_image* image) {
    return g_texture_create_filtered(image, SG_FILTER_LINEAR, SG_FILTER_LINEAR);
}

g_texture* g_texture_create_filtered(g_image* image, sg_filter min_filter, sg_filter mag_filter) {
    sg_image sg_img = sg_make_image(&(sg_image_desc){
        .width = image->width,
        .height = image->height,
        .data.subimage[0][0] = { 
            .ptr = image->pixels, 
            .size = image->width * image->height * image->channels
        },
        .pixel_format = SG_PIXELFORMAT_RGBA8 // has to be used for opengl support
    });

    sg_sampler sg_samp = sg_make_sampler(&(sg_sampler_desc){ 
        .min_filter = min_filter,
        .mag_filter = mag_filter
    });

    g_texture* texture = calloc(1, sizeof(g_texture));
    if(texture != NULL) {
        log_info("Texture allocated successfully");
        log_debug("Texture pointer: %p", texture);

        texture->width = image->width;
        texture->height = image->height;
        texture->image = sg_img;
        texture->sampler = sg_samp;
    } else {
        log_fatal("Failed to allocate texture");
        exit(EXIT_FAILURE);
    }

    g_image_destroy(image);

    return texture;
}
