// 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

import LocalStorage from "../Data/LocalStorage";
import { ScreenName } from "../UI/Screen/ScreenUI";
import UIManager from "../UI/UIManager";
import DataLevel from "./DataLevel";
import MapManager from "./MapManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameManager extends cc.Component {

    @property(UIManager)
    uiManager: UIManager = null;

    dataLevels: DataLevel[] = [];
    wormTry: number = 0;

    public static Instance: GameManager = null;

    async onLoad() {
        GameManager.Instance = this;
        await this.initialize();
    }

    protected start(): void {
    }

    async initialize() {
        this.dataLevels = await this.loadLevel() as DataLevel[];
        this.uiManager.initialize(this);
        this.backHone();
    }

    backHone() {
        this.uiManager.activeScreen(ScreenName.MAINMENU);
    }

    async loadLevel() {
        return new Promise(function (resolve, reject) {
            cc.loader.loadRes("Data/LevelConfigs", (err, objects) => {
                if (err) {
                    cc.log('Error when loading JSON:', err);
                    reject([]);
                }
                let dataLevels = objects.json.map((object: any) => {
                    let dataLevel = new DataLevel();
                    Object.assign(dataLevel, object);
                    return dataLevel;
                });
                resolve(dataLevels);
            });
        })
    }


    playGame(level: number){
        //let idBackground = this.getIDBackground(level);
        // LocalStorage.setBackground(idBackground);
        // this.uiManager.setBackground(idBackground);
        MapManager.Instance.generateMapByLevel(level);
    }

    getIDBackground(n: number): number {
        if (n < 1) {
          throw new Error("Số truyền vào phải lớn hơn hoặc bằng 1");
        }
      
        // Tính toán ID theo quy tắc
        return Math.floor((n - 1) % 3) + 1;
      }
}