package speiger.src.coreengine.rendering.utils;

import org.lwjgl.opengl.GL11;

import speiger.src.coreengine.math.collision2d.Plane;
import speiger.src.coreengine.rendering.guiOld.helper.box.IGuiBox;
import speiger.src.coreengine.utils.io.GameLog;

public class ScissorsManager
{
	Plane[] instances;
	int inUse = -1;
	
	public ScissorsManager(int limit) {
		instances = new Plane[limit];
		for(int i = 0;i<limit;i++) {
			instances[i] = new Plane();
		}
	}
	
	public void push(int x, int y, int width, int height) {
		if(inUse + 1 >= instances.length) {
			GameLog.warn("Scissors test would go out of Bounds!");
			return;
		}
		inUse++;
		if(inUse == 0) {
			instances[inUse].set(x, y, x + width, y + height);
			GL11.glEnable(GL11.GL_SCISSOR_TEST);
			GL11.glScissor(x, y, width, height);
			return;
		}
		Plane oldBox = instances[inUse - 1];
		Plane box = instances[inUse].set(Math.max(x, oldBox.getMinX()), Math.max(y, oldBox.getMinY()), Math.min(x + width, oldBox.getMaxX()), Math.min(y + height, oldBox.getMaxY()));
		GL11.glScissor(box.getMinX(), box.getMinY(), box.getWidth(), box.getHeight());
	}
	
	public boolean contains(IGuiBox box) {
		return inUse == -1 || instances[inUse].isIntersecting((int)box.getMinX(), (int)box.getMinY(), (int)box.getMaxX(), (int)box.getMaxY());
	}
	
	public boolean contains(int x, int y, int width, int height) {
		return inUse == -1 || instances[inUse].isIntersecting(x, y, x + width, y + height);
	}
	
	public void pop() {
		if(inUse < 0) {
			GameLog.warn("Scissors test would go into negative");
			return;
		}
		inUse--;
		if(inUse >= 0) {
			Plane box = instances[inUse];
			GL11.glScissor(box.getMinX(), box.getMinY(), box.getWidth(), box.getHeight());
			return;
		}
		GL11.glDisable(GL11.GL_SCISSOR_TEST);
	}
}
