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

const { ccclass, property } = cc._decorator;

@ccclass
export default class Loading extends cc.Component {

    @property(cc.ProgressBar)
    loadingBar: cc.ProgressBar = null;
    @property(cc.Label)
    loadingLabel: cc.Label = null;

    progress: number = 0;

    protected start(): void {
        cc.director.preloadScene("Game", this.onProgress.bind(this), this.onLoaded);
    }

    onProgress(completedCount, totalCount, item) {
        let count = completedCount / totalCount;
        if (this.progress < count) {
            this.loadingBar.progress = count;
            this.loadingLabel.string = `Loading ${Math.round(count * 100)}%`;
            this.progress = count;
        }
    }

    onLoaded(error: Error) {
        if (!error) {
            cc.director.loadScene("Game");
        } else {
            console.error("Failed to preload scene: ", error);
        }
    }

}
