package speiger.src.coreengine.math.collision2d;

import java.util.Iterator;

import speiger.src.coreengine.math.vector.ints.Vec2i;

public class Mixed2DCollision implements I2DCollision
{
	I2DCollision mainBox;
	I2DCollision[] subBoxes;
	
	public Mixed2DCollision(I2DCollision mainBox, I2DCollision...subBoxes) {
		this.mainBox = mainBox;
		this.subBoxes = subBoxes;
	}
	
	@Override
	public boolean isColliding(int x, int y) {
		return mainBox.isColliding(x, y) && isCollidingInSubBox(x, y);
	}
	
	public boolean isCollidingInSubBox(int x, int y) {
		for(int i = 0,m=subBoxes.length;i<m;i++) {
			if(!subBoxes[i].isColliding(x, y)) return false;
		}
		return true;
	}
	
	@Override
	public Iterator<Vec2i> iterator() {
		return new Iterator<Vec2i>(){
			Iterator<Vec2i> mainIter = mainBox.iterator();
			Vec2i cache = findNext(Vec2i.mutable());
			Vec2i result = Vec2i.mutable();
			@Override
			public boolean hasNext() {
				return cache != null;
			}

			@Override
			public Vec2i next() {
				result.set(cache);
				cache = findNext(cache);
				return result;
			}
			
			Vec2i findNext(Vec2i input) {
				while(mainIter.hasNext()) {
					Vec2i next = mainIter.next();
					if(isCollidingInSubBox(next.x(), next.y())) return input.set(next);
				}
				return null;
			}
		};
	}
	
}
