
package {
	import com.netgrind.core.Utils;
	import adobe.utils.CustomActions;
	import com.bit101.components.Panel;
	import com.bit101.components.PushButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.Dictionary;
	
	/**
	 * ...
	 * @author netgrind
	 */
	public class Handle extends Sprite {
		
		public static var all:Vector.<Handle> = new Vector.<Handle>();
		
		private var _color:uint = 0xff00ff;
		public var size:int = 15;
		
		public var canMove:Boolean = true;
		public var moving:Boolean = true;
		public var callback:Function;
		private var _snap:int = 5;
		private var menu:Array = [];
		
		public function Handle(x:int, y:int,movementCallback:Function) {
			all.push(this);
			this.x = x;
			this.y = y;
			callback = movementCallback;
			Main.debugLayer.addChild(this);
			addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			draw();
			addEventListener(MouseEvent.MOUSE_DOWN, onDown);
			addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, onRightDown);			
		}
		
		public function addMenuItem(name:String, callback:Function, ...params):void {
			menu.push([name, callback,params]);
		}
		
		private function onRightDown(e:MouseEvent):void {
			e.stopPropagation();
			ContextMenu.targetSprite(this, menu);
		}
		
		private function onDown(e:MouseEvent):void {
			e.stopPropagation();
			if (!canMove) return;
			moving = true;
			stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
			stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
		}
		
		private function onUp(e:MouseEvent):void {
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
			stage.removeEventListener(MouseEvent.MOUSE_UP, onUp);
		}
		
		private function onMove(e:MouseEvent):void {
			x = e.stageX-Level.offset.x;
			y = e.stageY-Level.offset.y;
			x -= x % snap;
			y -= y % snap;
			callback();
		}
		
		public function draw():void {
			graphics.clear();
			graphics.beginFill(color);
			graphics.drawCircle(0, 0, size * .5);
			graphics.endFill();
		}
		
		public static function draw():void {
			for each(var h:Handle in all) {
				h.draw();
			}
		}
		public static function hide():void {
			for each(var h:Handle in all) {
				h.visible = false;
			}
		}
		public static function show():void {
			for each(var h:Handle in all) {
				h.visible = true;
			}
		}
		
		public function kill():void {
			var i:int = all.indexOf(this);
			if (i != -1) all.splice(i, 1);
			Utils.removeChild(this);
		}
		
		public function get snap():int {
			return _snap;
		}
		
		public function set snap(value:int):void {
			_snap = value;
			x -= x % _snap;
			y -= y % _snap;
		}
		
		public function get color():uint {
			return _color;
		}
		
		public function set color(value:uint):void {
			_color = value;
			draw();
		}
		
	}
	
}