import { ModuleTypes } from "../types/sceneTypes";
import Scene from "../components/Scene";
import Loading from "../components/Loading";
export default class SceneCtrl {
    private _parent: egret.Sprite;
    private _currentScene: Scene;
    private _mask: egret.Sprite;

    static _instance: SceneCtrl;
    static get instance() {
        return SceneCtrl._instance || (SceneCtrl._instance = new SceneCtrl())
    }
    init(parent: egret.Sprite) {
        this._parent = parent;
    }

    change(type: ModuleTypes, data?, onComplete?: Function) {
        const cls = this._sceneClassMap[type];
        const scene: Scene = new cls();
        if (!window['development']) {
            Loading.instace.show();
            const key = scene.skinKey.toLowerCase();
            const promise = Promise.all([
                RES.getResAsync(`${key}_json`),
                RES.getResAsync(`${key}_png`)]);
            promise.then(() => {
                this.showAfterLoadAtlas(scene, data, onComplete);
            });
        } else {
            this.showAfterLoadAtlas(scene, data, onComplete);
        }
    }

    showAfterLoadAtlas(scene: Scene, data, onComplete: Function) {
        Loading.instace.hide();
        if (this._currentScene) {
            const oldScene = this._currentScene;
            oldScene.destroy();
            this._parent.removeChild(oldScene);
        }
        scene.loadSkin();
        scene.addEventListener(egret.Event.ADDED_TO_STAGE, () => {
            scene.start();
        }, this);
        this.addToStage(scene);
        onComplete && onComplete();
    }

    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);
    }

    private addToStage(scene: Scene) {
        this._currentScene = scene;
        this._parent.addChild(scene);
    }

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

    get currentScene(){
        return this._currentScene
    }
}