package search;

import flash.geom.Point;

class ToolSub extends Tool
{
	var coords:Point;
	var findTime:Float;
	var foundTarget:Target;
	var foundCoords:Point;
	var startTime:Float;
	public var done(default,null):Bool;

	public static var kErrorRate = 0;
	public static var kFindRadius = 0.25;

	public function new(area_:Area, c0:Point, c1:Point=null)
	{
		super(area_, kErrorRate);
		super.makePixelSprite("Tool-Sub.png");
		coords = c0;
		findTime = 0;
		startTime = clock.time;
	}

	public override function update()
	{
		super.update();

		if (foundTarget != null)
		{
			if (!done && clock.time > findTime)
			{
				done = true;
				Util.playSound("Rescued.mp3");
				pixelSprite.loadGraphic("assets/images/Tool-Rescued.png");
				coords = foundCoords;
				var foundTargetWasAlreadyRecovered = foundTarget.recovered;
				foundTarget.recovered = true;
				area.registerSubFinished(foundTarget, !foundTargetWasAlreadyRecovered);
			}
		}
		else if ((clock.time - startTime) < 5)
		{
			// look for nearby target

			// make findRadius a little bigger for huge maps
			var findRadius = Util.lerpScale(area.dim.x, 20, 60, kFindRadius, 2*kFindRadius);

			for (target in targets)
			{
				if (Util.dist(coords, target.getCoords(clock)) < findRadius)
				{
					findTime = clock.time + Util.lerp(3, 5, Math.random());
					foundCoords = target.getCoords(clock);
					foundTarget = target;
					break;
				}
			}
		}
		else
		{
			// couldn't find anything
			done = true;
			area.registerSubFinished(null, false);
		}

		if (done && foundTarget != null)
		{
			Util.setPos(pixelSprite, area.coordsToScreen(coords));
			pixelSprite.x += (Math.random() < 0.5 ? -1 : 1);
			pixelSprite.y += (Math.random() < 0.5 ? -1 : 1);
			pixelSprite.x = Math.floor(pixelSprite.x - pixelSprite.width/2);
			pixelSprite.y = Math.floor(pixelSprite.y - pixelSprite.height/2);
		}
		else
		{
			super.updatePixelSprite(coords, 8);
		}
	}

	public override function draw()
	{
	}
}
