package GraphicExport
{
	import Defs.GraphicDef;
	import flash.display.MovieClip;
	import djarts.utils.*;
	import djarts.display.GraphicFactory;
	import CharacterExport.*;
	
	public class AnimPiecePacker
	{
		protected var doneCallback;
		protected var callbackParam;
		protected var holder:MovieClip;

		public function AnimPiecePacker(callback, callbackParam, holder:MovieClip)
		{
			this.doneCallback = callback;
			this.callbackParam = callbackParam;
			this.holder = holder;
		}
		
		protected var defs:Array;
		public function ExportDefs(defs:Array)
		{
			this.defs = defs;
			
			ExportNextDef();
		}
		
		protected function ExportNextDef()
		{
			if (defs.length == 0)
			{
				Done();
			}
			else
			{
				var def:GraphicDef = defs.splice(0, 1)[0];
				var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);});
			}
		}
		
		protected var toExport:Array = new Array();
		
		protected function GraphicCallback(c, g, def:GraphicDef)
		{
			if (g is MovieClip)
			{
				var pieceSet:AnimationPieceSet = new AnimationPieceSet();
				pieceSet.Name = def.Name;
				toExport.push(pieceSet);
				pieceSet.LoadClip(g, ExportNextDef);
			}
			else
			{
				ExportNextDef();
			}
		}
		
		protected function Done()
		{
			var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport);
			
			if (doneCallback) doneCallback(builder.Output, callbackParam);
		}
	}
}