package search;

import flash.geom.Point;

class Spottings
{
	var clock:Clock;
	var spottings:Array<SearchSpotting> = [];

	public var blind:Bool = false;
	public var hasLiving(get,never):Bool;

	public function new(clock_:Clock)
	{
		clock = clock_;
	}

	public function add(coords:Point, duration:Float, ?userData:Dynamic, overrideUserDataIfSameCoords:Bool=true)
	{
		if (blind) return;

		// reset existing
		for (spotting in spottings)
		{
			if (Util.dist(spotting.coords, coords) < 0.01)
			{
				spotting.time = clock.time;
				if (overrideUserDataIfSameCoords)
					spotting.userData = userData;
				return;
			}
		}

		// re-use dead
		for (spotting in spottings)
		{
			if (!spotting.isAlive(clock))
			{
				spotting.time = clock.time;
				spotting.duration = duration;
				spotting.coords = coords;
				spotting.userData = userData;
				return;
			}
		}

		// add new
		spottings.push(new SearchSpotting(clock.time, duration, coords, userData));
	}

	public function getAlive():Array<SearchSpotting>
	{
		var aliveSpottings = new Array<SearchSpotting>();
		for (spotting in spottings)
		{
			if (spotting.isAlive(clock)) aliveSpottings.push(spotting);
		}
		return aliveSpottings;
	}

	function get_hasLiving():Bool
	{
		for (spotting in spottings)
		{
			if (spotting.isAlive(clock)) return true;
		}
		return false;
	}
}

class SearchSpotting
{
	public var time:Float;
	public var coords:Point;
	public var duration:Float;
	public var userData:Dynamic;

	public function new(time_:Float, duration_:Float, coords_:Point, userData_:Dynamic)
	{
		time = time_;
		duration = duration_;
		coords = coords_;
		userData = userData_;
	}

	public function getAge(clock:Clock):Float { return (clock.time - time) / duration; }
	public function isAlive(clock:Clock):Bool { return getAge(clock) < 1.0; }
}

