import { _decorator, Component, Label, lerp, Prefab, ProgressBar, } from "cc";
import { PREVIEW } from "cc/env";
import { UIMgr } from "../Module/UIMgr";
import { changeScene } from "db://assets/Module/UIFast";
import { MusicBtn } from "../Component/MusicBtn/MusicBtn";
import ZipLoader from "./ZipLoader";
import store from "../Scripts/store/store";
import { getPreLoadList, preload } from "../Scripts/Utils/LoaderTools";
import { AudioMgr } from "../core_tgx/base/AudioMgr";
import { LOG_TYPE, sendLog } from "../Scripts/Utils/WebNet/WebNet";
import shareStore from "../Scripts/store/shareStore";
import { HomeScene } from "db://assets/Scripts/Scenes/HomeScene";

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);

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

        document.getElementById("GameDiv").style.overflow = "visible";
        // MusicBtn.open = false;

        sendLog(LOG_TYPE.EXPOSURE, 1);

        await store.updateFrontVariable();
        shareStore.doShare(false);

    }

    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.1, 0.3);

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

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

        await store.updateIndex();

        await changeScene(HomeScene, { from: "Loading" });
        // await changeScene(RankScence);

        AudioMgr.ins.play("audio/秒来劲", {
            loop: true,
            bundleName: "common",
        });
    }

}


