package GraphicExport
{
	import CharacterExport.*;
	import Defs.GraphicDef;
	import flash.display.MovieClip;
	import djarts.utils.*;
	
	
	public class SkelAnimPacker
	{
		
		protected var library:PieceLibrary;
		protected var waiter:CountWaiter;
		
		protected var exporters:Array = new Array();
		
		protected var defs:Array = new Array();
		
		protected var doneCallback;
		protected var callbackParam;
		protected var holder:MovieClip;
		protected var defaultExportType;
		protected var scale:Number = 1;
		
		protected var outputFormat = "binary";
		
		public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary")
		{
			this.doneCallback = callback;
			this.callbackParam = callbackParam;
			this.holder = holder;
			this.defaultExportType = defaultExportType;
			this.scale = scale;
			this.outputFormat = outputFormat;
		}
		
		public function ExportDefs(defs:Array)
		{
			this.defs = defs;
			
			library = new PieceLibrary();
			
			ExportNext();
		}
		
		var removeClips:Array = new Array();
		
		protected var currentDef:GraphicDef;
		protected function ExportNext(...rest)
		{
			if (holder)
			{
				for (var i in removeClips)
				{
					if (removeClips[i].parent)
					{
						removeClips[i].parent.removeChild(removeClips[i]);
					}
				}
				removeClips.splice(0);
				
				for (var i = 0; i < holder.numChildren; i++)
				{
					removeClips.push(holder.getChildAt(i));
				}				
			}
			if (defs.length == 0)
			{
				Done();
				return;
			}
			
			currentDef = defs.shift();
			
			var exporter:CharacterExporter = new CharacterExporter(holder);
			exporters.push(exporter);
			
			exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale);
		}
		
		var exporter:ExportBuilder;
		protected function Done()
		{
			this.library.EnsureAllUsedPiecesHaveNames();
			
			exporter = new ExportBuilder(exporters, -1, -1, library);
			
			if (outputFormat == "json_png_set")
			{
				if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam);
			} else {
				if (doneCallback) doneCallback(exporter.Output, callbackParam);
			}
		}
		
		protected function JSONSaveComplete()
		{
			if (doneCallback) doneCallback(exporter.Output, callbackParam);
		}
	}
}