package
{
	import flash.utils.*;
	import flash.display.*;
	import flash.system.LoaderContext;
	import flash.events.*;
	import by.blooddy.crypto.*;
	import flash.system.SecurityDomain;

	public class GraphicExportDef
	{
		private var _exportType:int = 1;
		public function get exportType():int { return _exportType; }
		
		private var _name:String = null;
		public function get name():String { return _name; }
		
		private var _valid:Boolean = false;
		public function get valid():Boolean { return _valid; }
		
		private var input:ByteArray;
		private var inputLoader:Loader = null;		
		
		private var parentJob:Job = null;
		
		private var callback = null;
		
		private var index:int = 0;
		
		public function GraphicExportDef(parentJob:Job, details, index:int)
		{
			this.parentJob = parentJob;
			this.index = index;
			if (!details.hasOwnProperty("type") || !details.hasOwnProperty("name") || !details.hasOwnProperty("input"))
			{
				Fail("graphic export is missing a required name, type, or input");
				return;
			}
			_exportType = parseInt(details.type);
			_name = "" + details.name;
			input = Base64.decode("" + details.input);
			_valid = true;
		}
		
		public function Fail(err:String)
		{
			parentJob.FailMessage("(" + index + ")" + err);
			if (callback != null) callback();
		}
		
		public function Go(callback)
		{
			this.callback = callback;
			
			inputLoader = new Loader();
			inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete);
			inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError);
			var context:LoaderContext = new LoaderContext();
			context.allowCodeImport = true;
			inputLoader.loadBytes(input, context);
		}
		
		private function LoaderComplete(e)
		{
			try
			{
				var classDef = e.target.applicationDomain.getDefinition(name);
				if (classDef == null)
				{
					Fail("didn't contain a definition for " + name);
					return;
				}
				
				var clip = new classDef();
				if (!(clip is MovieClip))
				{
					Fail(name + " wasn't a movieclip");
				}
				
				Utils.RecursivelyStop(clip);
				
				Done();
			} catch (e)
			{
				Exporter.Instance.Print(e.getStackTrace());
			}
		}
		private function LoaderError(e)
		{
			Fail("couldn't load input: " + e.toString());
		}
		public function Done()
		{			
			this.callback();
		}
	}
}