package;

import haxe.Resource;
import search.Area;
import flash.geom.Point;
import flixel.util.FlxRect;
import flixel.util.FlxPoint;
import flixel.FlxG;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.text.FlxText;
import flixel.ui.FlxButton;
import flixel.util.FlxMath;

class PlayState extends FlxState
{
	var searchArea:Area;
	var clockSprite:ClockSprite;
	var draggingIcon:DraggingIcon;
	var toolNameText:FlxText;

	override public function create():Void
	{
		super.create();

		searchArea = new Area(new FlxRect(5, 5, 500, 260), new Point(PrepareState.config.dim.x, PrepareState.config.dim.y), PrepareState.config);
		searchArea.whenDone = searchArea_onDone;
		add(searchArea.group);

		var background = new FlxSprite(0,0);
		background.loadGraphic("assets/images/Screen-Search.png");
		add(background);

		var stacks = new Array<IconStack>();
		var stackX = 150;
		for (toolConfig in PrepareState.selectedToolConfigs)
		{
			var toolSpec = ToolSpec.Helper.find(toolConfig.id);
			var stack = new IconStack(new FlxPoint(stackX, 296), toolSpec, toolConfig.count);
			stackX += Math.floor(((stack.width+5)/10))*10+10;
			stacks.push(stack);
			add(stack);
		}

		clockSprite = new ClockSprite();
		clockSprite.setPosition(4, 260);
		add(clockSprite);

		var backButton = new ImageButton(17, 314, "Button-SearchAbort.png", backButton_onClick);
		add(backButton);

		toolNameText = Util.makeText("", 100, Main.GREEN, "left");
		toolNameText.x = 400;
		toolNameText.y = 272;
		toolNameText.visible = false;
		add(toolNameText);

		draggingIcon = new DraggingIcon(stacks, null, searchArea.placer);
		add(draggingIcon);

		draggingIcon.whenMouseDown = draggingIcon_whenMouseDown;

		Main.playMusic("Ocean.mp3");
	}

	function draggingIcon_whenMouseDown(icon:Icon)
	{
		var spec = (icon == null) ? null : icon.toolSpec;
		if (spec != null)
		{
			toolNameText.text = spec.name;
			toolNameText.visible = true;
		}
		else
		{
			toolNameText.visible = false;
		}
	}

	function backButton_onClick()
	{
		FlxG.switchState(new PrepareState());
	}

	function searchArea_onDone()
	{
		ResultState.numSaved = searchArea.numPeopleSaved;
		ResultState.numLost = (PrepareState.config.numTargets * PrepareState.config.numPeoplePerTarget) - ResultState.numSaved;
		ResultState.numWrecksFound = searchArea.numTargetsRecovered;
		FlxG.switchState(new ResultState());
	}

	override public function destroy():Void
	{
		draggingIcon.whenMouseDown = null;
		searchArea.whenDone = null;
		super.destroy();
	}

	override public function update():Void
	{
		super.update();
		searchArea.update();

		clockSprite.t = Util.lerpScale(searchArea.clock.time, 0, searchArea.config.timeLimit, 0, 1);

		if (FlxG.keys.justReleased.SPACE)
			FlxG.switchState(new PlayState());
	}
}