import {
    _decorator, AssetManager,
    assetManager,
    Component,
    director,
    Label,
    lerp,
    Node,
    Prefab,
    profiler,
    ProgressBar,
    resources,
} from "cc";
import { PREVIEW } from 'cc/env';
import { UIMgr } from "../Module/UIMgr";
import { changeScene, showToast } from "db://assets/Module/UIFast";
import { AudioMgr } from "../core_tgx/base/AudioMgr";
import { MusicBtn } from "../Component/MusicBtn/MusicBtn";
import ZipLoader from "./ZipLoader";
import store from '../Scripts/store/store';
import { getPreLoadList, preload } from "../Scripts/Utils/LoaderTools";
import { runMainPage } from "../Scripts/Scenes/runMain/runMainPage";
import ShareCenter from "../Scripts/ShareCenter";
import { initWx } from "../Scripts/Utils/Share";

const { ccclass, property } = _decorator;

const _FPS = 61;

@ccclass("Start")
export class Start extends Component {

    @property(Prefab)
    uiPrefab: Prefab;

    @property(ProgressBar)
    progressBar: ProgressBar;

    @property(Label)
    progressTxt: Label = null;

    async onLoad() {
        // game.frameRate = _FPS;

        // 预览调试时，显示性能统计面板
        if (PREVIEW) {
            profiler.showStats();
        }
        // profiler.hideStats();

        UIMgr.ins.setup(this.uiPrefab);

        document.body.style.visibility = "visible";

        MusicBtn.open = localStorage.getItem("MusicStatus") != "false";
        // MusicBtn.open = false;

        await store.updateFrontVariable();

        await initWx();
        ShareCenter.ins.doShare('main');
    }

    onDestroy() {
    }

    setProgress = (progress: number) => {
        this.progressBar.progress = progress;
        // this.progressTxt.string = `加载中（${Math.round(progress * 100)}%）…`;
    }

    loadZipBundle(from: number, to: number) {
        const zipBundle = window["zipBundle"] || [];
        let loaded = 0;
        const loadZipPs = zipBundle.map((name: any) => {
            return ZipLoader.ins.loadZip(`${window["__remoteUrl__"]}remote/${name}`)
                .then(() => {
                    loaded++;
                    this.setProgress(lerp(from, to, loaded / zipBundle.length));
                });
        });
        return Promise.all(loadZipPs);
    }

    async start() {
        this.setProgress(0.05);

        await this.loadZipBundle(0.05, 0.3);

        const pkg = [
            {
                path: "common",
                type: "bundle",
            },
            // {
            //     path: "runMainPage",
            //     type: "bundle"
            // },
            // {
            //     path: "runGamePage",
            //     type: "bundle"
            // },
        ];

        const list = await getPreLoadList(pkg, this.setProgress, 0.05, 0.2);

        await preload(list, this.setProgress, 0.2, 1);

        await changeScene(runMainPage);
    }

}


