package {
	import adobe.utils.CustomActions;
	import flash.display.Sprite;
	import nape.geom.Vec2;
	
	/**
	 * ...
	 * @author netgrind
	 */
	public class Waypoint extends Sprite {
		
		public static var all:Vector.<Waypoint> = new Vector.<Waypoint>();
		
		public var waypointName:String;
		public var handle:Handle;
		
		public var isUsed:Boolean = false;
		public var requireStop:Boolean = true;
		public var waitTime:int = 1000;//in ms
		public var position:Vec2 = new Vec2();
		public var speed:Number = .95;
		
		
		public function Waypoint(x:int,y:int, name:String) {
			super();
			waypointName = name;
			all.push(this);
			position.x = this.x = x;
			position.y = this.y = y;
			handle = new Handle(x,y, onMove);
			handle.color = 0x00ff00; 
		}
		
		private function onMove():void {
			position.x = x = handle.x;
			position.y = y = handle.y;
		}
		
		public function saveString():String {
			var s:String = "";
			s += x + "|" + y;
			return s;
		}
		
		public static function createFromString(s:String):Waypoint {
			var a:Array = s.split("|");
			return new Waypoint(a[0],a[1],a[2]);
		}
		
		public static function getUnused():Waypoint {
			var i:int = Math.floor(Math.random() * Waypoint.all.length);
			var j:int = i;
			var w:Waypoint = Waypoint.all[i];
			while (w.isUsed) {
				i++;
				i %= Waypoint.all.length;
				if (i == j) return null;
				w = Waypoint.all[i];
			}
			return w;
		}
		
		public static function getFromName(name:String):Waypoint {
			for (var i:int = 0; i < all.length; i++) {
				if (all[i].waypointName == name) return all[i];
			}
			trace("ERROR: Waypoint " + name+" not found");
			return null;
		}		
	}
	
}