package search;

import search.Spottings.SearchSpotting;
import flixel.FlxSprite;
import flash.geom.Point;
import flixel.util.FlxPoint;

class Tool
{
	var area:Area;
	var errorRate:Float;
	var canvas:CanvasSprite;
	var pixelSprite:FlxSprite;
	var hasTarget:Bool;
	var spottings:Spottings;

	public var clock(get,never):Clock;
	public var targets(default,null):Array<Target>;

	public function new(area_:Area, errorRate_:Float)
	{
		area = area_;

		// disable error rate
		// it might work better with a more nuanced design. As is, it just looks like a bug
		//errorRate = errorRate_;
		errorRate = 0;

		canvas = area.makeCanvasSprite();
		spottings = new Spottings(clock);

		targets = new Array<Target>();
		for (target in area.targets)
		{
			if (Math.random() > errorRate)
			{
				// no error, get actual target
				targets.push(target);
			}
			else
			{
				// error, add random target
				targets.push(new Target(area));
			}
		}

		// add one more random target in rare cases
		if (Math.random() < errorRate*0.25)
		{
			targets.push(new Target(area));
		}

		hasTarget = (targets.length != 0);
	}

	function getRandomTargetCoords():Point
	{
		return hasTarget ? targets[Std.int(targets.length * Math.random())].getCoords(clock) : new Point(1000,1000);
	}

	public function destroy()
	{
		canvas.destroy();
		if (pixelSprite != null) pixelSprite.destroy();
	}

	public function update()
	{
	}

	public function draw()
	{
	}

	inline function get_clock()
	{
		return area.clock;
	}

	public function makePixelSprite(imageFilename:String)
	{
		pixelSprite = new FlxSprite(0,0);
		pixelSprite.loadGraphic("assets/images/" + imageFilename);
		area.group.add(pixelSprite);
	}

	public function updatePixelSprite(coords:Point, speed:Float=1)
	{
		if (pixelSprite != null)
		{
			Util.setPos(pixelSprite, area.coordsToScreen(coords));
			pixelSprite.y += 2 * Math.cos(speed * clock.time);
			pixelSprite.x = Math.floor(pixelSprite.x - pixelSprite.width/2);
			pixelSprite.y = Math.floor(pixelSprite.y - pixelSprite.height/2);
		}
	}
}
