import { ModuleTypes } from "../types/sceneTypes";
import Panel from "../views/Panel";
import Loading from "../loading/Loading";
export default class PanelCtrl {
    private _parent: eui.UILayer;
    private _mask: egret.Shape;
    private panelsArr:Panel[];
    public isLoadedMsg:boolean;
    static _instance: PanelCtrl;
    static get instance() {
        return PanelCtrl._instance || (PanelCtrl._instance = new PanelCtrl())
    }

    init(parent: eui.UILayer) {
        this._parent = parent;
    }

    show(type: ModuleTypes, data?, hasMask:boolean = true) {
        const cls = this._panelClassMap[type];
        
        Loading.instace.show();
        const panel: Panel = new cls(data, hasMask);
        this._current = panel;
        // panel.setSkinName();
        // panel.setMask();
        // panel.setShowAct();
        // panel.start(data);
        if(!this.panelsArr){
            this.panelsArr = [];
        }
        this.panelsArr.push(panel);
        this.add(panel);

        this._parent.visible = true;
    }

    private add(panel: Panel) {
        this._parent.addChild(panel);
        panel.addEventListener('onDestroy', this.onPanelHide, this);
        // panel.addEventListener('onCreditsOut', this.onCreditsOut, this);
    }

    private remove(panel: Panel) {
        this._parent.removeChild(panel);
    }

    private onPanelHide(e: egret.Event) {
        const panel = e.target as Panel;
        panel.removeEventListener('onDestroy', this.onPanelHide, this);
        // panel.removeEventListener('onCreditsOut', this.onCreditsOut, this);
        this.remove(panel);

        var pidx:number = this.panelsArr.indexOf(panel);
        if(pidx != -1){
            this.panelsArr.splice(pidx, 1);
        }

        if(this._parent.numChildren == 0){
            this._parent.visible = false;
        }
    }

    public removeAllPanel():void{
        if(!this.panelsArr){
            return;
        }
        for(var i:number = 0; i < this.panelsArr.length; i++){
            this.panelsArr[i].hidePanel();
        }
    }

    // private onCreditsOut(e: egret.Event){
    //     if(!window['CFG'] || !window['CFG'].appInfo) return;
    //     window.location.href = window['CFG'].appInfo.earnCreditsUrl;
    // }

    private _panelClassMap: any;
    registerPanelClass(name, definition) {
        this._panelClassMap = this._panelClassMap || {};
        this._panelClassMap[name] = definition;
    }

    
    private _current: Panel;

    closeCurrent() {
        if (this._current)
            this.remove(this._current);
    }
}