package speiger.src.coreengine.rendering.texturesOld.stb;

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

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import org.lwjgl.stb.STBImage;
import org.lwjgl.system.MemoryUtil;

import speiger.src.coreengine.assets.AssetLocation;
import speiger.src.coreengine.assets.base.IAsset;
import speiger.src.coreengine.assets.parsers.NativeMemoryParser;
import speiger.src.coreengine.rendering.texturesOld.base.AbstractTexture;
import speiger.src.coreengine.rendering.texturesOld.base.TextureManager;

public class STBTexture extends AbstractTexture
{
	AssetLocation location;
	long imageData;
	int width;
	int height;
	
	public STBTexture(AssetLocation location)
	{
		this.location = location;
//		loadTexture();
	}
	
	private void loadTexture()
	{
		try(IAsset asset = TextureManager.INSTANCE.getManager().getAsset(location))
		{
			ByteBuffer buffer = asset.custom(NativeMemoryParser.INSTANCE);
			int[] width = new int[1];
			int[] height = new int[1];
			int[] fileChannels = new int[1];
			ByteBuffer image = STBImage.stbi_load_from_memory(buffer, width, height, fileChannels, 4);
			if(image == null) {
				MemoryUtil.memFree(buffer);
				throw new IOException("Could not load image: " + STBImage.stbi_failure_reason());
			}
			imageData = MemoryUtil.memAddress(image);
			this.width = width[0];
			this.height = height[0];
			MemoryUtil.memFree(buffer);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return;
		}
		setTextureID(GL11.glGenTextures());
		bindTexture();
		GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
		GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
		GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL13.GL_CLAMP_TO_BORDER);
		GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL13.GL_CLAMP_TO_BORDER);
		GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imageData);
		GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
	}
	
	@Override
	public int getWidth()
	{
		return width;
	}
	
	@Override
	public int getHeight()
	{
		return height;
	}
	
	@Override
	public void reload()
	{
		if(imageData != 0) 
		{
			STBImage.nstbi_image_free(imageData);
			imageData = 0;
		}
		int old = textureID;
		loadTexture();		
		TextureManager.INSTANCE.removeTexture(old);
	}
	
	@Override
	public void deleteTexture()
	{
		super.deleteTexture();
		if(imageData != 0) 
		{
			STBImage.nstbi_image_free(imageData);
			imageData = 0;
		}
	}
}
