package search;

import flixel.FlxSprite;
import flixel.util.FlxColor;
import flash.geom.Point;
import flash.display.Graphics;

class ToolFlyby extends ToolBoats
{
	var kSmearLenMax:Float = 2;
	var kSpottingDuration:Float = 6;

	public static var kErrorRate = 0.15;
	public static var kAcquireTime = 20;
	public static var kLineWidth = 5;

	public function new(area_:Area, c0:Point, c1:Point)
	{
		super(area_, kErrorRate);

		var plane = new Boat(area,
			"Tool-Plane.png",
			0.05, // speed
			kLineWidth*0.5, // sightRadius
			targets
		);
		plane.setWaypoints([c0, c1, c0, c1, c0, c1]);
		plane.whenFoundTargetAndGetShouldLoiter = plane_onFoundTarget;
		addBoat(plane, false);
	}

	private function plane_onFoundTarget(target:Target):Bool
	{
		var smearLen = Math.random() * 0.5*kSmearLenMax * (Math.random() > 0.5 ? 1 : -1);
		var smearOffset = Util.mul(smearLen, boats[0].getHeading());
		var smearCenter = Util.add(target.getCoords(clock), smearOffset);
		var smearDir = Util.mul(kSmearLenMax, boats[0].getHeading());
		var smear = new Smear(
			Util.sub(smearCenter, smearDir),
			Util.add(smearCenter, smearDir)
		);
		spottings.add(target.getCoords(clock), kSpottingDuration, smear, false);
		return false; // don't loiter
	}

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

	public override function update()
	{
		super.update();
		canvas.visible = clock.getFlashing(3) && spottings.hasLiving;
	}

	public override function draw()
	{
		if (spottings.hasLiving)
		{
			var aliveSpottings = spottings.getAlive();
			var patternBitmapData = openfl.Assets.getBitmapData("assets/images/Pattern-Flyby.png");
			canvas.clear();

			for (spotting in aliveSpottings)
			{
				if (spotting.getAge(clock) > 1) continue;

				var numSmearSpots = 8;
				var radiusMax = kSmearLenMax / numSmearSpots;
				var smear = cast(spotting.userData, Smear);
				for (i in 0...numSmearSpots)
				{
					var t = i / (numSmearSpots-1.0);
					var p = Util.plerp(smear.p0, smear.p1, t);
					var r = radiusMax * Util.lerp(0.25, 1, Math.sin(t * Math.PI));
					var graphics = canvas.beginPatternDraw(patternBitmapData, false);
					graphics.drawCircle(p.x, p.y, r);
					canvas.endDraw();
				}
			}
		}
	}
}

class Smear
{
	public var p0:Point;
	public var p1:Point;
	public function new(p0_:Point, p1_:Point) { p0 = p0_; p1 = p1_; }
}
