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();
            RES.getResByUrl(`${scene.skinKey.toLowerCase()}_json`, (sheet: egret.SpriteSheet) => {
                Loading.instace.hide();
                this.showAfterLoadAtlas(scene, data, onComplete);
            }, this, RES.ResourceItem.TYPE_SHEET);
        } else {
            this.showAfterLoadAtlas(scene, data, onComplete);
        }
    }

    showAfterLoadAtlas(scene: Scene, data, onComplete: Function) {
        if (this._currentScene) {
            this._currentScene.destroy();
            this._parent.removeChild(this._currentScene);
        }
        scene.loadSkin();
        scene.start();
        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;
    }
}