import MPanel from "../MViews/MPanel";
import Loading from "../../loading/Loading";
export default class MTopLayerCtrl {
    private _parent: eui.Group;
    private _mask: egret.Shape;

    static _instance: MTopLayerCtrl;
    static get instance() {
        return MTopLayerCtrl._instance || (MTopLayerCtrl._instance = new MTopLayerCtrl())
    }

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

    show(cls: any, data?: any, hasMask: boolean = true, time: number = 2500) {
        Loading.instace.show();
        const panel: MPanel = new cls(data, hasMask, time);
        this._current = panel;
        this.add(panel);
        this._parent.visible = true;
    }

    /**
     * 防止连点
     * @param targe 可交互对象
     * @param dtime 延时默认500ms
     */
    public btnDelay(targe: any, dtime: number = 500) {
        targe.touchEnabled = false;
        setTimeout(() => {
            targe.touchEnabled = true;
        }, dtime);
    }

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

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

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

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

    private panelHide(panel: MPanel): void {
        panel.removeEventListener('onDestroy', this.onPanelHide, this);
        this.remove(panel);

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

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


    private _current: MPanel;

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