import { EventDispatcher } from "../../engines/events/EventDispatcher";
import IInitiator from "../../engines/initiators/IInitiator";
import InitiatorEvent from "../../engines/initiators/InitiatorEvent";
import LoadingView from "../../engines/loadingView/LoadingView";


export default class LoadingViewInitiator extends EventDispatcher implements IInitiator
{
    private __layerRoot:cc.Node;
    private __loadingViewPackage:string;
    private __loadingViewResName:string;

    constructor(layerRoot:cc.Node,loadingViewPackage:string,loadingViewResName:string){
        super();
        this.__loadingViewPackage=loadingViewPackage;
        this.__loadingViewResName=loadingViewResName;
        this.__layerRoot=layerRoot;
    }


    Start(): void {
        this.InitLayers();
        fgui.UIPackage.loadPackage(cc.resources,this.__loadingViewPackage,this.OnLoadingViewLoadComplete.bind(this));
    }

    private InitLayers():void{
        if(this.__layerRoot==null){
            throw new Error("layerRoot==null");
        }
        fgui.GRoot.create(this.__layerRoot);
        this.CreateLayers(10);
    }

    /**
     * 初始化层
     * @param count 
     */
    private CreateLayers(count:number):void{
        let layer:fgui.GComponent;
        for (let index = 0; index < count; index++) {
            layer=new fgui.GComponent();
            layer.node.name=index.toString();
            layer.name=index.toString();
            fgui.GRoot.inst.addChild(layer);
        }
    }

    private OnLoadingViewLoadComplete(err:Error):void{
        if(err){
            throw new Error("加载LoadingView出错"+this.__loadingViewPackage+this.__loadingViewResName);
        }
        let view:fgui.GComponent=fgui.UIPackage.createObject(this.__loadingViewPackage,this.__loadingViewResName).asCom;
        let progressBar:fgui.GProgressBar=view.getChild("progressBar") as fgui.GProgressBar;
        let label:fgui.GLabel=view.getChild("label") as fgui.GLabel;
        LoadingView.single.Init(view,progressBar,label);
        LoadingView.single.Show();

        //完成
        this.DispatchEvent(InitiatorEvent.EVENT_COMPLETE);
    }

    Destroy(): void {
        this.__layerRoot=null;
    }

    GetName(): string {
        return "LoadingViewInitiator";
    }
}