package search;

import flash.geom.Point;
import flixel.FlxSprite;


class ToolSonicBuoy extends Tool
{
	public static var kMaxRadius = 3;
	public static var kErrorRate = 0.15;
	public static var kPulseDuration = 1;
	public static var kPulseDelay = 0.5;

	var coords:Point;
	var radius:Float;
	var pulseTime:Float;
	var pulseHitRadius:Float;

	public function new(area_:Area, c0:Point, c1:Point=null)
	{
		super(area_, kErrorRate);
		super.makePixelSprite("Tool-SonicBuoy.png");

		coords = c0;
		pulseTime = 0;
		pulseHitRadius = 1000;
	}

	public override function destroy()
	{
		super.destroy();
	}

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

		pulseTime += clock.dt;
		if (pulseTime < kPulseDuration)
		{
			// draw pulse
			var radius = Util.lerpScale(pulseTime, 0, kPulseDuration, 0, kMaxRadius);
			if (radius >= pulseHitRadius)
			{
				// made a spotting
				spottings.add(new Point(pulseHitRadius, Util.lerp(0.1, 0.5, Math.random())), 2 * (kPulseDuration + kPulseDelay));
				spottings.blind = true;
			}
		}
		else if (pulseTime > kPulseDuration + kPulseDelay)
		{
			// start new pulse
			pulseTime = 0;
			pulseHitRadius = 10000;
			for (target in targets)
			{
				pulseHitRadius = Math.min(pulseHitRadius, Util.dist(coords, target.getCoords(clock)));
			}

			spottings.blind = false;
		}
	}

	public override function draw()
	{
		canvas.clear();

		if (pulseTime < kPulseDuration)
		{
			// draw pulse
			var radius = Util.lerpScale(pulseTime, 0, kPulseDuration, 0, kMaxRadius);
			var graphics = canvas.beginPatternDraw(openfl.Assets.getBitmapData("assets/images/Pattern1.png"), false);
			graphics.drawCircle(coords.x, coords.y, radius);
			graphics.drawCircle(coords.x, coords.y, radius - area.onePixel);
			canvas.endDraw();
		}

		for (spotting in spottings.getAlive())
		{
			// draw spotting ring
			var graphics = canvas.beginPatternDraw(openfl.Assets.getBitmapData("assets/images/Pattern1.png"), false);
			graphics.drawCircle(coords.x, coords.y, spotting.coords.x + spotting.coords.y*0.5);
			graphics.drawCircle(coords.x, coords.y, spotting.coords.x - spotting.coords.y*0.5);
			canvas.endDraw();
		}
	}
}
