package ;

import flash.geom.Point;
import flixel.util.FlxPoint;
import flixel.group.FlxGroup;

class IconStack extends FlxGroup
{
	public var pos(default,set):FlxPoint;
	public var toolSpec(default,null):ToolSpec;
	public var width(default,null):Float;
	public var height(default,null):Float;

	public function new(pos_:FlxPoint, toolSpec_:ToolSpec, numIcons:Int)
	{
		super();

		pos = pos_;
		toolSpec = toolSpec_;
		height = 0;

		for (i in 0...numIcons)
		{
			var icon = new Icon(new FlxPoint(pos.x+i*2,pos.y+i*2), this, toolSpec.iconFilename);
			width = icon.width + i*2;
			height = Math.max(height, icon.height + i*2);
			add(icon);
		}
	}

	function set_pos(p:FlxPoint):FlxPoint
	{
		pos = p;
		var i = 0;
		for (m in 0...members.length)
		{
			var member = members[m];
			if (!Std.is(member, Icon)) continue;
			cast(member, Icon).setPosition(pos.x+i*2, pos.y+i*2);
			i++;
		}
		return p;
	}

	public static function rightAlignStacks(stacks:Array<IconStack>, startIndex:Int, rightX:Float)
	{
		if (startIndex >= stacks.length) return;

		// get total width
		var totalWidth = stacks[stacks.length-1].pos.x + stacks[stacks.length-1].width - stacks[startIndex].pos.x;

		var curLeftX = stacks[startIndex].pos.x;
		var newLeftX = rightX - totalWidth;

		for (i in startIndex...stacks.length)
		{
			var stack = stacks[i];
			stack.pos = new FlxPoint(newLeftX + (stack.pos.x - curLeftX), stack.pos.y);
		}
	}

	public function grabIcon(pos:FlxPoint):Icon
	{
		var icons = new Array<Icon>();
		for (m in this)
		{
			if (Std.is(m, Icon)) icons.push(cast m);
		}

		if (icons.length == 0) return null;

		var topIcon = cast(icons[icons.length-1], Icon);
		if (topIcon.overlapsPoint(pos))
		{
			remove(topIcon);
			return topIcon;
		}
		else
		{
			return null;
		}
	}

	public function putIcon(icon:Icon)
	{
		add(icon);
		members.sort(function(a, b) {
			if (a == icon) return 1;
			if (b == icon) return -1;
			return 0;
		});
		var i=0;
		for (m in this)
		{
			cast(m, Icon).setPos(new FlxPoint(pos.x+i*2, pos.y+i*2), m==icon);
			i++;
		}
	}
}
