package speiger.src.coreengine.platform.graphics.opengl.core;

import java.util.OptionalLong;

import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL33;
import org.lwjgl.opengl.GL45;

import speiger.src.coreengine.platform.graphics.api.core.TimeQueryPool;

public class GLTimeQueryPool implements TimeQueryPool {
	boolean removed = false;
	int[] queries;
	
	public GLTimeQueryPool(int size) {
		this.queries = new int[size];
		GL45.glCreateQueries(GL33.GL_TIMESTAMP, queries);
	}
	
	@Override
	public boolean isRemoved() {
		return removed;
	}
	
	@Override
	public void remove() {
		if(removed) return;
		GL15.glDeleteQueries(queries);
		removed = true;
	}
	
	@Override
	public int size() {
		return queries.length;
	}
	
	@Override
	public void write(int index) {
		GL33.glQueryCounter(queries[index], GL33.GL_TIMESTAMP);
	}
	
	@Override
	public OptionalLong get(int index) {
		if(GL15.glGetQueryObjectui(queries[index], GL15.GL_QUERY_RESULT_AVAILABLE) == 1) {
			return OptionalLong.of(GL33.glGetQueryObjectui64(queries[index], GL15.GL_QUERY_RESULT));
		}
		return OptionalLong.empty();
	}
	
}
