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

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

import speiger.src.coreengine.rendering.utils.values.GLBlendFactor;
import speiger.src.coreengine.rendering.utils.values.IGLValue.IDestinationFactor;
import speiger.src.coreengine.rendering.utils.values.IGLValue.ISourceFactor;

public class BlendState extends GLState
{
	int srcRGB = GLBlendFactor.ONE.glValue();
	int destRGB = GLBlendFactor.ZERO.glValue();
	int srcAlpha = GLBlendFactor.ONE.glValue();
	int destAlpha = GLBlendFactor.ZERO.glValue();
	
	public BlendState() {
		super(GL11.GL_BLEND);
	}
	
	private void setFunction(int srcRGB, int srcAlpha, int destRGB, int destAlpha) {
	      if (this.srcRGB != srcRGB || this.srcAlpha != srcAlpha || this.destRGB != destRGB || this.destAlpha != destAlpha) {
	    	  this.srcRGB = srcRGB;
	    	  this.srcAlpha = srcAlpha;
	    	  this.destRGB = destRGB;
	    	  this.destAlpha = destAlpha;
	    	  GL15.glBlendFuncSeparate(srcRGB, destRGB, srcAlpha, destAlpha);
	      }
	}
	
	private void setFunction(int src, int dest) {
	      if (this.srcRGB != src || this.destRGB != dest) {
	    	  this.srcRGB = src;
	    	  this.destRGB = dest;
	    	  GL11.glBlendFunc(src, dest);
	      }
	}
	
	public BlendState setFunction(ISourceFactor srcRGB, ISourceFactor srcAlpha, IDestinationFactor destRGB, IDestinationFactor destAlpha) {
		setFunction(srcRGB.glValue(), srcAlpha.glValue(), destRGB.glValue(), destAlpha.glValue());
		return this;
	}
	
	public BlendState setFunction(ISourceFactor src, IDestinationFactor dest) {
		setFunction(src.glValue(), dest.glValue());
		return this;
	}
	
	@Override
	public void reapply() {
		super.reapply();
		GL15.glBlendFuncSeparate(srcRGB, destRGB, srcAlpha, destAlpha);
	}
	
	public void setDefault() {
		setFunction(GL11.GL_ONE, GL11.GL_ONE);
	}
}
