package net.fdms.Action 
{
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	/**
	 * 动作处理
	 * @author Dawnboy
	 */
	public class Action 
	{
		private static var _action:Array = [];
		private static var _dispatch:Function = null;
		private static var _param:* = null;
		private static var timerQueue:Array = [];
		public function Action()
		{
			
		}
		
		/**
		 * 添加方法
		 * @param	action
		 */
		public static function addAction(action:Array):void {
			_action = action;
		}
		
		/**
		 * 执行动作
		 * @param	action
		 */
		public static function start(dispatchFun:Function = null, param:* = null):void {
			//MouseAction.MouseActionOff();
			_dispatch = dispatchFun;
			_param = param;
			var n:int = _action.length;
			
			/** 生成动作计时器 **/
			for (var a:int = 0; a < n; a++ ) {
				var actTimer:Timer = new Timer(Number(_action[a][2] * 1000), 1);
				timerQueue.push(actTimer);
				actTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerHandler);
				actTimer.start();
			}
			
			/**全局计时器,计算最大值,控制全局**/
			var maxTime:Number = getMaxTimer() * 1000 + 500;
			var EndTimer:Timer = new Timer(maxTime,1);
			EndTimer.addEventListener(TimerEvent.TIMER_COMPLETE, dispatchHandler);
			EndTimer.start();
			
		}
		
		/**
		 * 获取附加载入动作
		 * @return
		 */
		public static function getLoadAction():Array {
			var n:int = _action.length;
			var foo:Array = [];
			for (var a:int =  0; a < n; a++ ) {
				if (_action[a][0] == 0) {
					foo.push(_action[a][1]);
				}

			}
			
			return foo;
		}
		
		/**
		 * 通知结束函数
		 */
		public static function dispatchHandler(e:TimerEvent):void {
			/** 清除计时器 **/
			e.target.stop();
			e.target.removeEventListener(TimerEvent.TIMER_COMPLETE, dispatchHandler);
			clearTimer();
			_action = [];
			
			//MouseAction.MouseActionOn();
			
			/**执行回调**/
			var foo:Function = _dispatch;
			var param:* = _param;
			_dispatch = null;
			_param = null;
			if (foo != null) {
				if (param) {
					foo(param);
				}else {
					foo();
				}
			}
		}
		
		/**
		 * 执行动作
		 * @param	actionID
		 */
		protected static function runAction(actionID:int):void {
			//try{
				ActionControl.runAction(_action[actionID][0], _action[actionID][1], _action[actionID][3]);
			//}catch (e:*) {
				
			//}
		}
		
		
		/**
		 * 计时器工具
		 * @param	e
		 */
		protected static function timerHandler(e:TimerEvent):void {
			e.target.stop();
			e.target.removeEventListener(TimerEvent.TIMER_COMPLETE, timerHandler);
			runAction(timerQueue.indexOf(e.target));
		}
		
		/**
		 * 获取最大计时单位
		 * @return
		 */
		protected static function getMaxTimer():Number {
			var n:int = _action.length;
			var tmp:Array = [];
			for (var a:int = 0; a < n; a++ ) {
				tmp.push(_action[a][2]);
			}
			tmp.sort(Array.NUMERIC);
			return tmp[tmp.length - 1];
		}
		
		/**
		 * 清空计时器
		 */
		protected static function clearTimer():void {
			var n:int = timerQueue.length;
			for (var a:int = 0; a < n; a++) {
				timerQueue[a] = null;
			}
			timerQueue = [];
		}
	}

}