package;

import search.Placer;
import flixel.util.FlxPoint;
import flixel.group.FlxGroup;
import flixel.FlxG;
import flash.events.MouseEvent;
import flixel.FlxSprite;

class DraggingIcon extends FlxGroup
{
	var draggingIcon(get,set):Icon;
	var grabPos:FlxPoint;
	var grabFromGrid:Bool;
	var grid:IconGrid;
	var stacks:Array<IconStack>;
	var placer:Placer;
	var mouseIsDown:Bool;

	public var whenMouseDown:Icon->Void;

	function get_draggingIcon() { return members.length != 0 ? cast(members[0], Icon) : null; }
	function set_draggingIcon(s:Icon) { clear(); if (s != null) add(s); return s; }

	public function new(stacks_:Array<IconStack>, grid_:IconGrid, placer_:Placer)
	{
		super();
		stacks = stacks_;
		grid = grid_;
		placer = placer_;

		if (placer != null)
			placer.whenDone = placer_onDone;
	}

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

	private function placer_onDone(icon:Icon, placed:Bool)
	{
		if (placed)
		{
			icon.destroy();
		}
		else
		{
			icon.originalStack.putIcon(icon);
		}
	}

	public override function update()
	{
		if (FlxG.mouse.pressed && !mouseIsDown) onMouseDown(null);
		if (!FlxG.mouse.pressed && mouseIsDown) onMouseUp(null);

		if (draggingIcon != null)
		{
			draggingIcon.x = FlxG.mouse.screenX - Std.int(draggingIcon.width/2);
			draggingIcon.y = FlxG.mouse.screenY - Std.int(draggingIcon.height/2);
			if (grid != null) grid.snap(draggingIcon);
			if (placer != null && draggingIcon.toolSpec.iconUseSecondFrameOnArea)
			{
				draggingIcon.frame = draggingIcon.framesData.frames[placer.wantIconSecondFrame() ? 1 : 0];
			}
		}

		super.update();
	}


	function onMouseDown(event:MouseEvent):Void
	{
		mouseIsDown = true;

		// check all stacks
		for (stack in stacks)
		{
			draggingIcon = stack.grabIcon(FlxG.mouse);
			if (draggingIcon != null) { grabFromGrid = false; break; }
		}

		if (draggingIcon == null && grid != null)
		{
			// check grid
			draggingIcon = grid.grabIcon(FlxG.mouse);
			grabFromGrid = true;
		}

		if (draggingIcon != null)
		{
			grabPos = new FlxPoint(draggingIcon.x, draggingIcon.y);
			if (placer != null) placer.begin(draggingIcon);
		}

		if (whenMouseDown != null)
			whenMouseDown(draggingIcon);
	}

	function onMouseUp(event:MouseEvent):Void
	{
		mouseIsDown = false;

		if (draggingIcon != null)
		{
			Util.playSound("Icon-Drop.mp3");

			// dropped
			var droppedIcon = draggingIcon;
			draggingIcon = null;

			if (grid != null && !grid.place(droppedIcon, grabFromGrid ? grabPos : null))
			{
				// put back in original stack
				droppedIcon.originalStack.putIcon(droppedIcon);
			}
		}
	}
}
