// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import SceneManager from "../../GEngine/scenes/SceneManager";
import GUIManager from "../../GEngine/gui/GUIManager";
import LoadingView from "../../GEngine/loadingView/LoadingView";
import LayerManager from "../../GEngine/gui/LayerManager";
import UIConst from "../gui/UIConst";

const {ccclass, property} = cc._decorator;

@ccclass
export default class PreloadingScene extends cc.Component {

    onLoad () {
        console.log("进入LoadingView场景");
    }

    start () {
        //UI全局节点
        let uiRoot:cc.Node=cc.find("UIRoot") as cc.Node;
        let layerRoot:cc.Node=cc.find("LayerRoot",uiRoot);

        cc.game.addPersistRootNode(uiRoot);

        this.InitLayers(layerRoot);
        this.InitGUI();

        //加载需要的
        this.LoadAssetBundles();
    }

    private InitLayers(layerRoot:cc.Node):void{
        LayerManager.single.Init(layerRoot);
    }

    

    private LoadAssetBundles():void{
        cc.assetManager.loadBundle("scenes",null,this.LoadScenesAssetBundleHandler.bind(this));
        cc.assetManager.loadBundle("ui",null,this.LoadUIAssetBundleHandler.bind(this));
    }

    private LoadScenesAssetBundleHandler(err: Error, bundle: cc.AssetManager.Bundle):void{
        if(err){
            console.error(err);
            return;
        }
        SceneManager.single.AssetBundle=bundle;
    }

    private LoadUIAssetBundleHandler(err:Error,bundle: cc.AssetManager.Bundle):void{
        if(err){
            console.error(err);
            return;
        }
        GUIManager.single.AssetBundle=bundle;
        this.CheckAllAssetBundleLoaded();
    }

    /**
     * 检测是否都加载完成
     */
    private CheckAllAssetBundleLoaded():void{
        if(SceneManager.single.AssetBundle!=null&&GUIManager.single.AssetBundle!=null){
            //进入赛前准备界面
            SceneManager.single.Swicth("PrepareScene");
            LoadingView.single.Hide();
        }
    }

    /**
     * 初始化GUI系统
     */
    private InitGUI():void{
        UIConst.RegisterGUI();
    }

    //假进度条
    private time:number=0;
    update (dt) {
        this.time+=dt;
        this.time=this.time%2;
        LoadingView.single.UpdateProgress(this.time/2);
    }
}