package client.renderer;

import java.nio.ByteBuffer;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;

public class VertexBuffer
{
    private int glBufferId;
    private final VertexFormat vertexFormat;
    private int count;

    public VertexBuffer(VertexFormat vertexFormatIn)
    {
        this.vertexFormat = vertexFormatIn;
        this.glBufferId = GL15.glGenBuffers();
    }

    public void bindBuffer()
    {
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, this.glBufferId);
    }

    public void bufferData(ByteBuffer buffer)
    {
        this.bindBuffer();
        GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
        this.unbindBuffer();
        this.count = buffer.limit() / this.vertexFormat.getNextOffset();
    }

    public void drawArrays(int mode)
    {
        GL11.glDrawArrays(mode, 0, this.count);
    }

    public void unbindBuffer()
    {
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
    }

    public void deleteGlBuffers()
    {
        if (this.glBufferId >= 0)
        {
            GL15.glDeleteBuffers(this.glBufferId);
            this.glBufferId = -1;
        }
    }
}
