package search;

import flash.geom.Rectangle;
import flash.geom.Point;

class ToolGps extends Tool
{
	var pass:Int;
	var passStartTime:Float;
	var searchingRect:Rectangle;

	static var kMaxPasses:Int = 3;
	static var kSpottingDuration:Float = 6;

	public static var kErrorRate:Float = 0.3;
	public static var kAcquireTime:Float = 10;

	public function new(area_:Area, c0:Point=null, c1:Point=null)
	{
		super(area_, kErrorRate);
		pass = 0;
		passStartTime = clock.time;
		searchingRect = new Rectangle(0,0,0,0);
	}

	public override function update()
	{
		if (pass >= kMaxPasses) return;

		var passDuration = Util.lerpScale(pass, 0, 3, 10, 5);
		var t = (clock.time - passStartTime) / passDuration;
		if (t >= 1.0)
		{
			t = 0;
			pass++;
			passStartTime = clock.time;
			if (pass >= kMaxPasses)
			{
				searchingRect = new Rectangle(0,0,0,0);
				canvas.clear();
				return;
			}
		}

		var div = Math.pow(2, Math.min(3, pass+1));
		var dimX = area.dim.x / div;
		var dimY = area.dim.y / div;
		var i = Math.floor(div * div * t);
		searchingRect.x = dimX * Math.floor(i % div);
		searchingRect.y = dimY * Math.floor(i / div);
		searchingRect.width = dimX;
		searchingRect.height = dimY;

		for (target in targets)
		{
			var targetCoords = target.getCoords(clock);
			if (searchingRect.containsPoint(targetCoords))
			{
				spottings.add(targetCoords, kSpottingDuration, searchingRect.clone());
			}
		}
	}

	public override function draw()
	{
		var graphics = canvas.beginPatternDraw(openfl.Assets.getBitmapData("assets/images/Pattern-Gps.png"));

		if (searchingRect.width > 0.1)
		{
			graphics.drawRect(searchingRect.x, searchingRect.y, searchingRect.width, searchingRect.height);
		}

		if (clock.getFlashing(5))
		{
			for (spotting in spottings.getAlive())
			{
				var rect = cast(spotting.userData, Rectangle);
				var inset = 3 * area.onePixel;
				graphics.drawRect(rect.x, rect.y, rect.width, rect.height);
				graphics.drawRect(rect.x+inset, rect.y+inset, rect.width-2*inset, rect.height-2*inset);
			}
		}

		canvas.endDraw();
	}
}
