import { Widget, _decorator, ProgressBar, math, macro } from 'cc';
import { UIBase } from '../scriptBase/UIBase';
import { Bundle } from '../enum/Bundle';
import { ResMgr } from '../manager/ResMgr';
import { UI } from '../enum/UI';
import { Setting } from '../Setting';
import { ItemMgr } from '../manager/ItemMgr';
import { AdMgr } from '../manager/AdMgr';
const { ccclass, property, requireComponent } = _decorator;

@ccclass('UI/UILoading')
@requireComponent(Widget)
export class UILoading extends UIBase {

    private progressBar: ProgressBar = null

    private loaded: boolean = false

    protected async onLoad() {
        this.progressBar = this.getComponentInChildren(ProgressBar)
    }

    protected async start() {
        this.schedule(this.updateProgress, 0.25, macro.REPEAT_FOREVER)
        await this.loadBundle()
        await this.loadRes()
        this.loaded = true
    }

    private init() {
        Setting.init()
        ItemMgr.init()
        AdMgr.init()
    }

    public onOpen(data?: any): void {
    }


    public onClose(data?: any): void {
    }

    private loadBundle() {
        return Promise.all([
            ResMgr.loadBundle(Bundle.Icon),
            ResMgr.loadBundle(Bundle.Audio),
            ResMgr.loadBundle(Bundle.Game),
            ResMgr.loadBundle(Bundle.UI),
        ])
    }

    private loadRes() {
        return Promise.all([
            ResMgr.loadDir(Bundle.Icon),
            ResMgr.loadDir(Bundle.Audio),
            ResMgr.loadDir(Bundle.Game),
            ResMgr.loadDir(Bundle.UI),
        ])
    }

    protected updateProgress(): void {
        let progressAdd: number = math.randomRange(0.1, 0.3)
        this.progressBar.progress = Math.min(this.progressBar.progress + progressAdd, 0.9)

        if (this.loaded) {
            this.progressBar.progress = 1.0
            this.unschedule(this.updateProgress)
            this.onLoadCompleted()
        }
    }

    private onLoadCompleted(): void {
        this.init()
        this.scheduleOnce(() => {
            this.close()
            this.open(UI.Main)
        }, 0.1)
    }

}


