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

		public function AnimSetPacker(callback, callbackParam, holder:MovieClip)
		{
			this.doneCallback = callback;
			this.callbackParam = callbackParam;
			this.holder = holder;
		}
		
		protected var avatarIndex = 0;
		protected var avatars:Array;
		public function ExportDef(def:GraphicDef)
		{
			avatarIndex = 0;
			avatars = def.ExportParams.avatars;
			DoNextAvatar();
		}
		
		private function DoNextAvatar()
		{
			if (avatarIndex >= avatars.length)
			{
				Done();
				return;
			}
			var avatar = avatars[avatarIndex];
			
			
			var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback);
		}
		
		protected var exporter:CharacterExporter;
		protected function GraphicCallback(c, g)
		{
			exporter = new CharacterExporter(holder);
			exporter.ProcessFromClip(g, ProductionDone);
		}
		
		protected var toExport:Array = new Array();		
		
		protected function ProductionDone()
		{
			var avatar = avatars[avatarIndex];
			var avatarName = avatar.avatar;
			var animations:Array = avatar.animations;
			
			for (var i in exporter.Sequences)
			{
				exporter.Sequences[i].AvatarName = avatarName;
				if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1)
				{
					toExport.push(exporter.Sequences[i]);
				}
			}
			
			avatarIndex++;
			
			//exporter.ProduceTemplate(DoNextAvatar);
			DoNextAvatar();
		}
		
		protected function Done()
		{
			var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport);
			
			if (doneCallback) doneCallback(builder.Output, callbackParam);
		}
	}
}