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

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

public class BufferAttachment implements IFrameAttachment
{
	int id;
	int format;
	int type;
	int samples;
	
	public BufferAttachment(int format)
	{
		this.format = format;
	}
	
	public static BufferAttachment createRGBA()
	{
		return new BufferAttachment(GL11.GL_RGBA);
	}
	
	public static BufferAttachment createRGB()
	{
		return new BufferAttachment(GL11.GL_RGB);
	}
	
	public static BufferAttachment createDepth()
	{
		return new BufferAttachment(GL11.GL_DEPTH_COMPONENT);
	}
	
	public static BufferAttachment createDepthStencil()
	{
		return new BufferAttachment(GL30.GL_DEPTH24_STENCIL8);
	}
	
	@Override
	public int getId()
	{
		return id;
	}
	
	public void setBufferId(int id)
	{
		if(this.id != id)
		{
			this.id = id;
			if(type != 0 && id != 0)
			{
				GL30.glFramebufferRenderbuffer(GL30.GL_FRAMEBUFFER, type, GL30.GL_RENDERBUFFER, id);
				GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, 0);
			}
		}
	}
	
	@Override
	public void init(int type, int width, int height, int samples)
	{
		this.type = type;
		this.samples = samples;
		if(id == 0)
		{
			id = GL30.glGenRenderbuffers();
		}
		GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, id);
		GL30.glRenderbufferStorageMultisample(GL30.GL_RENDERBUFFER, samples, format, width, height);
		GL30.glFramebufferRenderbuffer(GL30.GL_FRAMEBUFFER, type, GL30.GL_RENDERBUFFER, id);
		GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, 0);
	}
	
	@Override
	public void delete()
	{
		if(id != 0)
		{
			GL30.glDeleteRenderbuffers(id);
		}
	}
	
}
