package speiger.src.coreengine.rendering.utils.states;

import java.util.BitSet;

import org.lwjgl.opengl.GL11;

public class GLState implements IGLState
{
	final int id;
	protected final boolean defaultValue;
	protected final BitSet memory = new BitSet();
	protected int index = -1;
	protected boolean lastState;
	
	public GLState(int id, boolean defaultValue)
	{
		this.id = id;
		this.defaultValue = defaultValue;
	}
	
	public GLState push(boolean newValue)
	{
		if((index < 0 && newValue != defaultValue) || (index >= 0 && memory.get(index) != newValue))
		{
			setValue(newValue);
		}
		memory.set(++index, newValue);
		return this;
	}
	
	public void pop()
	{
		if(index < 0) throw new IllegalStateException("State is already reset");
		if(index == 0 && defaultValue != memory.get(0))
		{
			setValue(defaultValue);
		}
		else if(index > 0 && memory.get(index-1) != memory.get(index))
		{
			setValue(memory.get(index-1));
		}
		index--;
	}
	
	public boolean isEnabled()
	{
		return index < 0 ? defaultValue : memory.get(index);
	}
	
	protected void setValue(boolean value)
	{
		if(value) GL11.glEnable(id);
		else GL11.glDisable(id);
	}
	
	@Override
	public void cleanup()
	{
		if(index > 0)
		{
			memory.set(0, memory.get(index));
			index = 0;
		}
	}
}
