import { _decorator, Component, Node, director, SceneAsset } from 'cc';
import { LoadingView } from '../loadingView/LoadingView';
const { ccclass, property } = _decorator;

export class SceneManager{
    private sceneName:string;
    /**
     * 切换场景
     * @param sceneName
     */
    public Swicth(sceneName:string):void{
        this.sceneName=sceneName;
        LoadingView.single.Show();
        console.log("切换到："+sceneName);
        LoadingView.single.UpdateLabel("切换到："+sceneName);
        director.preloadScene(sceneName,this.OnProgressHandler.bind(this),this.OnCompleteHandler.bind(this))
    }

    private OnProgressHandler(completedCount: number, totalCount: number, item: any):void{
        LoadingView.single.UpdateProgress(completedCount/totalCount);
    }

    private OnCompleteHandler(error: null | Error, sceneAsset?: SceneAsset):void{
        if(error!=null){
            console.error(this.sceneName+"加载错误："+error);
            LoadingView.single.UpdateLabel(this.sceneName+"加载错误："+error);
        }
        director.loadScene(this.sceneName);
        LoadingView.single.Hide();
    }

    private static instance:SceneManager;
    public static get single(){
        if(this.instance==null){
            this.instance=new SceneManager();
        }
        return this.instance;
    }
}
