package vocaloplus.threads
{
	import com.seacolorswind.dbi.AirDao;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import jp.seagirl.genius.threads.GeniusThread;
	import mx.events.ModuleEvent;
	import mx.modules.IModuleInfo;
	import mx.modules.ModuleManager;
	import vocaloplus.entities.ModuleDef;

	/**
	 * ...
	 * @author Kazushi Tominaga (Seacolor)
	 */
	public class LoadModuleThread extends GeniusThread
	{
		/**
		 * モジュールです。
		 */
		protected var _module:IModuleInfo;

		/**
		 * モジュールの定義情報を格納したデータベースです。
		 */
		protected var _db:AirDao;

		private var _type:String;
		public function LoadModuleThread(db:AirDao, id_or_name:Object, type:String)
		{
			if (! (id_or_name is int || id_or_name is String)) throw new ArgumentError();
			trace("constructor(", arguments, ")");
			_db = db;
			data = id_or_name;
			_type = type;
		}

		override protected function run():void
		{
			trace("run");
			if (data == null) throw new ArgumentError();

			if (data is int) {
				_db.read(ModuleDef, moduleInfoReaded, { module_id: int(data), type: _type } );
			} else if (data is String) {
				_db.read(ModuleDef, moduleInfoReaded, { name: String(data), type: _type } );
			} else {
				throw new ArgumentError();
			}
			wait();
		}

		protected function moduleInfoReaded(result:Array):void {
			trace("moduleInfoReaded(", arguments, ")");
			if (!result.length) throw new Error("module is not found.");

			var _moduleInfo:ModuleDef = result[0];
			if (!_moduleInfo || !_moduleInfo.url) throw new ArgumentError();
			_module = ModuleManager.getModule(_moduleInfo.url);
			event(_module, ModuleEvent.READY, moduleReady);
			_module.load();

			notify();
		}

		protected function moduleReady(event:ModuleEvent):void {
			trace("moduleReady(", arguments, ")");
		}

		public function get module():Object
		{
			return _module.factory.create();
		}
	}

}
