import * as mc from "@minecraft/server";
import * as utils from "./utils/index";
const VERSION = "1.0.0";
const START = mc.system.currentTick;
mc.world.afterEvents.playerSpawn.subscribe(event => updateMenu(new utils.SafetyCheckedPlayer(event.player)));
mc.system.afterEvents.scriptEventReceive.subscribe(event => {
    if (event.id === utils.GlobalNamespace.Namespace + "update" && event.sourceEntity instanceof mc.Player) {
        resetUpdate(new utils.SafetyCheckedPlayer(event.sourceEntity));
    }
});
utils.getAllPlayersSafe().forEach(updateMenu);
export function resetUpdate(player) {
    utils.writeDynamicProperty(player, "version", "0.0.0");
    updateMenu(player);
}
async function updateMenu(player) {
    // Wait for UI to become available, estimated 15 seconds for most devices
    do {
        await utils.waitForWorldLoad();
        await utils.waitForTicks(20);
    } while (mc.system.currentTick <= START + (15 * 20));
    // Show menu to players with different version value
    const playerVersion = utils.readDynamicProperty(player, "version");
    if (playerVersion !== undefined && playerVersion.slice(0, 3) !== VERSION.slice(0, 3)) {
        // Set player's gamemode to spectator to protect them while menu is open
        // const mode = player.getGameMode();
        // player.setGameMode(mc.GameMode.spectator);
        new utils.ButtonMenu({ translate: utils.GlobalNamespace.Namespace + "update.version.name" }, [
            {
                text: { translate: utils.GlobalNamespace.Namespace + "update.update.button" },
                onClick(player) {
                    // Only save version when they confirm they have read the message
                    // utils.writeDynamicProperty<string>(player, "version", VERSION);
                },
            }
        ], { translate: utils.GlobalNamespace.Namespace + "update.update.body", with: ["\n"] })
            // // Restore the player's original gamemode on menu close
            // .onCancel((player) => player.setGameMode(mode))
            // .onClose((player) => player.setGameMode(mode))
            .showMenuToPlayer(player);
        utils.writeDynamicProperty(player, "version", VERSION);
    }
    else {
        utils.writeDynamicProperty(player, "version", VERSION);
    }
}
