
import { Scene } from "../views/Scene";
import { showWaiting, hideWaiting } from "./waitingCtrl";
import { Container } from "../../engine/2d/display";
import { showToast } from "./toastCtrl";


export default class SceneCtrl {

    private _parent: Container;
    private _currentScene: Scene;

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

    change(cls: any, data?: any) {
        //如果是同一个场景，考虑是替换还是return
        if (this._currentScene && this._currentScene instanceof cls) return;
        let scene: Scene = new cls(data);
        scene.visible = false;
        showWaiting();
        let preScene: Scene = this._currentScene;
        scene.onLoaded = () => {
            hideWaiting();
            scene.showAni(() => {
                if (preScene) preScene.destroy();
            })
            scene.visible = true;
            //start里可能处理资源信息，所以在onLoaded后执行
            scene.start();
        }
        //加载失败，继续用之前的场景，移除scene
        scene.onLoadError = () => {
            hideWaiting();
            showToast("资源加载失败")
            this._currentScene = preScene || null;
            this._parent.removeChild(scene);
        }

        this._currentScene = scene;
        this._parent.addChild(scene);
    }

    get currentScene() {
        return this._currentScene
    }

    destroy() {
        SceneCtrl._instance = null;
        this._currentScene = null;
        this._parent = null;
    }
}