import { EventDispatcher } from "../events/EventDispatcher";
import { GUIManager } from "../gui/GUIManager";
import IInitiator from "./IInitiator";
import InitiatorEvent from "./InitiatorEvent";



/**
 * UI 初始化
 */
export default class FGUIInitiator extends EventDispatcher implements IInitiator{

   
    private __commonUIAB:string;
    private __commonUI:string;

    constructor(commonUIAB:string,commonUI:string){
        super();
        this.__commonUI=commonUI;
        this.__commonUIAB=commonUIAB;
    }

    Start(): void {
        this.CheckCommonUI();
    }

    private CheckCommonUI():void{
        let bundle:cc.AssetManager.Bundle=cc.assetManager.getBundle(this.__commonUIAB);
        if(bundle==null){
            cc.assetManager.loadBundle(this.__commonUIAB,this.OnCommonUIABLoadComplete.bind(this))
        }else{
            this.LoadCommonUI(bundle);
        }
    }

    private OnCommonUIABLoadComplete(err:Error,bundle:cc.AssetManager.Bundle):void{
        if(err){
            throw new Error("公共UI资源包加载出错:"+this.__commonUIAB);
        }
        this.LoadCommonUI(bundle);
    }

    private LoadCommonUI(bundle:cc.AssetManager.Bundle):void{
        fgui.UIPackage.loadPackage(bundle,this.__commonUI,(err:Error,bundle)=>{
            if(err){
                throw new Error("AssetBundle中不存在："+this.__commonUI);
            }
            this.DispatchEvent(InitiatorEvent.EVENT_COMPLETE);
        })
    }
    
    Destroy(): void {
        
    }
    
    GetName(): string {
        return "FGUIInitiator";
    }
}