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

import speiger.src.collections.floats.lists.FloatArrayList;
import speiger.src.collections.floats.lists.FloatList;

public abstract class FloatState implements IGLState
{
	protected final float defaultValue;
	protected FloatList states = new FloatArrayList();
	
	public FloatState(float defaultValue)
	{
		this.defaultValue = defaultValue;
	}
	
	public void push(float newValue)
	{
		if((states.isEmpty() && equalsNot(newValue, defaultValue)) || (states.size() > 0 && equalsNot(states.getFloat(states.size()-1), newValue)))
		{
			setValue(newValue);
		}
		states.add(newValue);
	}
	
	public void pop()
	{
		if(states.isEmpty()) throw new IllegalStateException("State is already reset");
		if(states.size() == 1 && equalsNot(defaultValue, states.getFloat(0)))
		{
			setValue(defaultValue);
		}
		else if(states.size() > 1 && equalsNot(states.getFloat(states.size()-2), states.getFloat(states.size()-1)))
		{
			setValue(states.getFloat(states.size()-2));
		}
		states.removeFloat(states.size()-1);
	}
	
	protected abstract void setValue(float value);
	
	protected abstract String getName();
	
	protected boolean equalsNot(float key, float value)
	{
		return Float.floatToIntBits(key) != Float.floatToIntBits(value);
	}
	
	@Override
	public void cleanup()
	{
		if(states.size() > 1)
		{
			float value = states.getFloat(states.size()-1);
			states.clear();
			states.add(value);
		}
	}
}
