package net.halbear.Terrain4J.EngineCore.Vulkan.Rendering.Pipeline;

import net.halbear.Terrain4J.EngineCore.Display.GLFWImageParser;
import net.halbear.Terrain4J.EngineCore.Vulkan.Rendering.Pipeline.Images.ImageSrc;
import org.lwjgl.system.MemoryStack;
import org.tinylog.Logger;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;

import static org.lwjgl.stb.STBImage.*;

public class GraphUtils {
    private GraphUtils(){ }

    public static void CleanImageData(ImageSrc imageSrc){
        Logger.debug("Loading Image Data [{}]",imageSrc.data());
        stbi_image_free(imageSrc.data());
    }

    public static ImageSrc LoadImage(String Filename) throws IOException{
        Logger.debug("Loading Image [{}]",Filename);
        ImageSrc newImage;
        ByteBuffer image;
        try (MemoryStack MemStack = MemoryStack.stackPush()) {
            IntBuffer channels = MemStack.mallocInt(1);
            IntBuffer width = MemStack.mallocInt(1);
            IntBuffer height = MemStack.mallocInt(1);
            image = stbi_load(Filename, width, height, channels, 4);
            if (image == null) {
                Logger.error("Could not load or find image inputted.");
                throw new IOException("Image file [" + Filename + "] not loaded: " + stbi_failure_reason());
            }
            newImage = new ImageSrc(image, width.get(0), height.get(0), channels.get(0));
        }
        Logger.debug("Loaded Buffer [{}]",image);
        return newImage ;
    }
}
