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

import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;

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

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

public class SimpleTexture extends AbstractTexture
{
	AssetLocation location;
	int width;
	int height;
	
	public SimpleTexture(AssetLocation location)
	{
		super();
		this.location = location;
		loadTexture();
	}
	
	public void loadTexture()
	{
		try(IAsset asset = TextureManager.INSTANCE.getManager().getAsset(location))
		{
			BufferedImage image = asset.texture();
			width = image.getWidth();
			height = image.getHeight();
			int[] pixelData = new int[width * height];
			image.getRGB(0, 0, width, height, pixelData, 0, width);
			ByteBuffer buffer = MemoryUtil.memAlloc(pixelData.length * 4);
			for(int y = 0;y<height;y++)
			{
				for(int x = 0;x<width;x++)
				{
					int pixel = pixelData[(y * width) + x];
					buffer.put((byte)((pixel >> 16) & 0xFF));
					buffer.put((byte)((pixel >> 8) & 0xFF));
					buffer.put((byte)(pixel & 0xFF));
					buffer.put((byte)((pixel >> 24) & 0xFF));
				}
			}
			
			buffer.flip();
			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, buffer);
			GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
			MemoryUtil.memFree(buffer);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	@Override
	public void reload()
	{
		int old = textureID;
		loadTexture();
		TextureManager.INSTANCE.removeTexture(old);
	}
	
	@Override
	public int getWidth()
	{
		return width;
	}
	
	@Override
	public int getHeight()
	{
		return height;
	}
}
