import * as mc from "@minecraft/server";
import * as utils from "../../utils/index";
import { showPostGameHint } from "../dialogue/hints";
import { OreGeneration } from "./ore_generation";
import { HEART_DATA } from "../../shared/heart_data";
utils.afterEvents.scriptEventRecieve.subscribe("ldz:set_postgame", event => {
    if (event.data) {
        triggerPostgame();
    }
    else {
        utils.setScore(".var", "PostGame", 0);
        OreGeneration.disable();
        // Disable recipes
        for (let index = 31; index < HEART_DATA.length; index++) {
            utils.runCommand(`/recipe take @a ${HEART_DATA[index].itemName}`);
        }
    }
});
/**
 * Post-game triggers on one of two conditions:
 * 1. The player has an Obtained_Count score of 30+ AND they dismount the jetpack.
 * 2. The player has an Obtained_Count score of 30+ AND they join the world with a JetpackDelay score existing indicating they've ridden it in the past.
 */
utils.waitForWorldLoad().then(checkPostgame);
function checkPostgame() {
    if (utils.getScoreAsBool(".var", "PostGame")) {
        OreGeneration.enable();
        return;
    }
    ;
    utils.afterEvents.scriptEventRecieve.subscribe("ldz:jetpack_start", async (event) => {
        var _a;
        if (event.sourceEntity) {
            const rideable = event.sourceEntity.getComponent("rideable");
            const rider = (_a = rideable === null || rideable === void 0 ? void 0 : rideable.getRiders()) === null || _a === void 0 ? void 0 : _a.at(0);
            if (rideable && rider instanceof mc.Player) {
                const player = new utils.SafetyCheckedPlayer(rider);
                await utils.waitForLoopEvent(20, () => !rideable.isValid() || rideable.getRiders().length < 1);
                if (player.getScore("Obtained_Count") >= 30) {
                    triggerPostgame();
                }
            }
        }
    });
    mc.world.afterEvents.playerSpawn.subscribe(event => {
        if (event.initialSpawn) {
            const player = new utils.SafetyCheckedPlayer(event.player);
            playerCheck(player);
        }
    });
    utils.getAllPlayersSafe().forEach(playerCheck);
    function playerCheck(player) {
        var _a;
        const objective = mc.world.scoreboard.getObjective("JetpackDelay");
        if (player.getScore("Obtained_Count") >= 30 && (objective === null || objective === void 0 ? void 0 : objective.hasParticipant((_a = player.scoreboardIdentity) !== null && _a !== void 0 ? _a : ""))) {
            triggerPostgame();
        }
    }
}
function triggerPostgame() {
    if (utils.getScoreAsBool(".var", "PostGame"))
        return;
    utils.setScore(".var", "PostGame", 1);
    utils.getAllPlayersSafe().forEach(showPostGameHint);
    OreGeneration.enable();
}
