import { ModuleTypes } from "../types/sceneTypes";
import Panel from "../components/Panel";
import Loading from "../components/Loading";
export default class PanelCtrl {
    private _parent: egret.Sprite;
    private _mask: egret.Sprite;
    static _instance: PanelCtrl;
    static get instance() {
        return PanelCtrl._instance || (PanelCtrl._instance = new PanelCtrl())
    }

    init(parent: egret.Sprite) {
        this._parent = parent;
    }

    show(type: ModuleTypes, data?) {
        const cls = this._panelClassMap[type];
        const panel: Panel = new cls(data);
        this.addMask();
        if (!window['development']) {
            Loading.instace.show();
            RES.getResByUrl(`${panel.skinKey.toLowerCase()}_json`, (sheet: egret.SpriteSheet) => {
                Loading.instace.hide();
                this.showAfterLoadAtlas(panel, data);
            }, this, RES.ResourceItem.TYPE_SHEET);
        } else {
            this.showAfterLoadAtlas(panel, data);
        }
        return panel;
    }

    showAfterLoadAtlas(panel: Panel, data) {
        panel.loadSkin();
        this._current = panel;
        panel.start(data);
        this.add(panel);
        egret.Tween.get(panel).set({ y: -200 }).to({ y: 0 }, 500, egret.Ease.getBackOut(2));
    }

    addMask() {
        if (!this._mask) {
            this._mask = new egret.Sprite();
            this._mask.touchEnabled = true;
            this._mask.graphics.beginFill(0, .7);
            this._mask.graphics.drawRect(0, 0, 750, 1624);
            this._mask.graphics.endFill();
        }
        this._mask.alpha = 1;
        this._parent.addChild(this._mask);
    }
    removeMask() {
        if (this._mask) {
            egret.Tween.get(this._mask).to({ alpha: 0 }, 200).call(
                () => this._parent.removeChild(this._mask), this);
        }
    }

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

    private remove(panel: Panel) {
        const tw = egret.Tween.get(panel);
        tw.to({ y: 1624 }, 400, egret.Ease.getBackIn(2))
            .call(() => {
                this._parent.removeChild(panel);
                this.removeMask();
            }, this);
    }

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

    private _panelClassMap: any;
    registerPanel(name, config) {
        this._panelClassMap = this._panelClassMap || {};
        this._panelClassMap[name] = config.cls;
    }


    private _current: Panel;

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