import { world, system, EntityInventoryComponent } from "@minecraft/server"

world.afterEvents.worldInitialize.subscribe(() => {

    const rnd_score = world.scoreboard.getObjective("cc_sga25_rnd_chest")
    if (!rnd_score) {
        system.run(() => {
            world.scoreboard.addObjective("cc_sga25_rnd_chest")
            world.scoreboard.addObjective("cc_sga25_rnd_effects")
        })
    }
    world.gameRules.commandBlockOutput = false


})

world.afterEvents.playerSpawn.subscribe(e => {
    const player = e?.player
    if (e.initialSpawn && !player.getTags().includes("cc_sga25:initialised")) {
        player.runCommand("structure load cc_sga25:guidebook ~ ~ ~ 0_degrees none true false")
        player.addTag("cc_sga25:initialised")
    }

})

function getGuidebook(container, player) {
    const size = 36;

    for (let i = 0; i < size; i++) {
        let item = container.getItem(i);
        if (item && item.typeId == "cc_sga25:guidebook") {

            player.runCommand("clear @s cc_sga25:guidebook 0 1");
            player.runCommand(
                "structure load cc_sga25:guidebook ~ ~ ~ 0_degrees none true false"
            );
            continue;
        }
    }
}

system.runInterval(() => {
    try {
        for (const player of world.getAllPlayers()) {

            if (!player) continue;
            const inv = player.getComponent(EntityInventoryComponent.componentId);

            if (!inv.container) continue;
            const container = inv.container;
            getGuidebook(container, player);
        }
    } catch (error) {
    }
}, 3);