
package {
	import com.netgrind.core.Utils;
	import com.bit101.components.Panel;
	import com.bit101.components.PushButton;
	import com.bit101.components.VBox;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	/**
	 * ...
	 * @author netgrind
	 */
	public class ContextMenu extends Panel {
		
		public static var i:ContextMenu;
		public var box:VBox;
		public var buttons:Vector.<PushButton>;
		
		public function ContextMenu(stage:Stage) {
			super(stage);
			if (i != null) {
				trace("THERE SHOULD ONLY BE ONE CONTEXT MENU");
				return;
			}
			i = this;
			box = new VBox(this);
			box.spacing = 1;
			buttons = new Vector.<PushButton>();
			stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
			visible = false;
		}
		
		private function onUp(e:MouseEvent):void {
			visible = false;
		}		
		
		public static function target(x:int, y:int, buttonInfo:Array):void {
			if (i == null) {
				trace("CONTEXT MENU NOT INITIALIZED");
				return;
			}
			i.x = x;
			i.y = y;
			var j:int;
			for (j = 0; j < buttonInfo.length; j++) {
				if (i.buttons.length <= j) i.buttons.push(new PushButton(i.box));
				i.buttons[j].label = buttonInfo[j][0];
				i.buttons[j].defaultHandler = buttonInfo[j][1];
				i.buttons[j].callbackParams = buttonInfo[j].length>3?null:buttonInfo[j][2];
			}
			for (var k:int = i.buttons.length - 1; k >= j; k-- ) {
				Utils.removeChild(i.buttons[k]);
				i.buttons[k] = null;
				i.buttons.splice(k, 1);
			}
			i.height = i.box.height;
			i.visible = true;
		}
		
		public static function targetSprite(sprite:Sprite, buttonInfo:Array):void {
			var p:Point = sprite.localToGlobal(new Point(0, 0));
			target(p.x, p.y, buttonInfo);
		}
		
	}
	
}