import LoadingView from "../loadingView/LoadingView";


export default class SceneManager
{
    private __assetBundleName:string;
    private __sceneName:string;
    private __switching:boolean;

    private get assetBundle():cc.AssetManager.Bundle{
        return cc.assetManager.getBundle(this.__assetBundleName);
    }
    /**
     * 切换场景
     * @param sceneName
     */
    Swicth(assetBundle:string,sceneName:string):void{
        LoadingView.single.Show();
        this.__assetBundleName=assetBundle;
        this.__sceneName=sceneName;
        this.__switching=true;
        if(this.assetBundle==null){
            cc.assetManager.loadBundle(this.__assetBundleName,this.OnAssetBundleLoadComplete.bind(this));
        }else{
            this.LoadScene();
        }
    }

    private OnAssetBundleLoadComplete(err:Error,asset:cc.AssetManager.Bundle):void{
        if(err){
            throw new Error("加载资源包出错："+this.__assetBundleName);
        }else{
            this.LoadScene();
        }
    }

    private LoadScene():void{
        this.assetBundle.loadScene(this.__sceneName,null,this.OnProgressHandler,this.OnCompleteHandler);
    }

    private OnProgressHandler(finish: number, total: number, item: cc.AssetManager.RequestItem):void{
        LoadingView.single.UpdateProgress(finish/total);
    }

    private OnCompleteHandler(error: Error, sceneAsset: cc.SceneAsset):void{
        if(error!=null){
            throw new Error("场景加载错误:"+this.__sceneName);
        }
        cc.director.runScene(sceneAsset);
        LoadingView.single.Hide();
    }

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