package speiger.src.coreengine.rendering.models.frameBuffer;

import java.nio.ByteBuffer;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL32;

import speiger.src.coreengine.rendering.texturesOld.base.TextureManager;

public class TextureAttachment implements IFrameAttachment
{
	int textureId;
	int format;
	int type;
	
	public TextureAttachment(int format)
	{
		this(0, format);
	}
	
	public TextureAttachment(int textureId, int format)
	{
		this.textureId = textureId;
		this.format = format;
	}
	
	public static TextureAttachment createRGBA()
	{
		return new TextureAttachment(GL11.GL_RGBA);
	}
	
	public static TextureAttachment createRGB()
	{
		return new TextureAttachment(GL11.GL_RGB);
	}
	
	public static TextureAttachment createDepth()
	{
		return new TextureAttachment(GL11.GL_DEPTH_COMPONENT);
	}
	
	public void setTexture(int textureId)
	{
		if(this.textureId != textureId)
		{
			this.textureId = textureId;
			if(type != 0 && textureId != 0)
			{
				TextureManager.bindTexture(textureId);
				GL32.glFramebufferTexture(GL30.GL_FRAMEBUFFER, type, textureId, 0);
				TextureManager.unbindTexture();				
			}
		}
	}
	
	@Override
	public int getId()
	{
		return textureId;
	}
	
	@Override
	public void init(int type, int width, int height, int samples)
	{
		this.type = type;
		if(textureId == 0)
		{
			textureId = GL11.glGenTextures();
			TextureManager.bindTexture(textureId);
			GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);
			GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, format, width, height, 0, format, GL11.GL_UNSIGNED_BYTE, (ByteBuffer)null);
			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);
		}
		else
		{
			TextureManager.bindTexture(textureId);
		}
		GL32.glFramebufferTexture(GL30.GL_FRAMEBUFFER, type, textureId, 0);
		TextureManager.unbindTexture();
	}
	
	@Override
	public void delete()
	{
		if(textureId != 0)
		{
			GL11.glDeleteTextures(textureId);
			textureId = 0;
		}
	}
}
