package speiger.src.coreengine.math.collision2d;

import java.util.Iterator;

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

public class Circle implements I2DCollision
{
	final Vec2i center;
	final int radius;
	
	public Circle(int x, int y, int radius)
	{
		center = Vec2i.newVec(x, y);
		this.radius = radius;
	}
	
	public Circle(Vec2i center, int radius)
	{
		this.center = center.asImmutable();
		this.radius = radius;
	}
	
	public Circle(Vec3i data)
	{
		this(data.getX(), data.getY(), data.getZ());
	}
	
	public Vec2i getCenter()
	{
		return center;
	}
	
	public int getRadius()
	{
		return radius;
	}
	
	@Override
	public boolean isColliding(int x, int y)
	{
		int xDiff = center.getX() - x;
		int yDiff = center.getY() - y;
		return ((xDiff * xDiff) + (yDiff * yDiff)) < radius * radius;
	}
	
	@Override
	public Iterator<Vec2i> iterator()
	{
		return new Iterator<Vec2i>(){
			Vec2i iter = step(Vec2i.newMutable(center).sub(radius));
			Vec2i result = Vec2i.newMutable();
			
			@Override
			public boolean hasNext()
			{
				return iter != null;
			}

			@Override
			public Vec2i next()
			{
				result.set(iter);
				iter = step(iter);
				return result;
			}
			
			Vec2i step(Vec2i iter)
			{
				while(iter != null)
				{
					iter.add(1, 0);
					if(iter.getX() >= center.getX() + radius)
					{
						iter.sub((radius * 2), 0).add(0, 1);
						if(iter.getY() >= center.getY() + radius)
						{
							iter = null;
						}
					}
					if(iter != null && isColliding(iter))
					{
						break;
					}
				}
				return iter;
			}
		};
	}	
}
