import {
    system,
    world
} from "@minecraft/server";
import {setBookLore} from "cubc/mo_en/enchants"
import {openEnchantMenu} from "cubc/mo_en/enchantmenu"
import {applyEnchantScoreboards, getRandomEnchant} from "cubc/mo_en/enchanthelpers"


// Apply our enchants every second
system.runInterval(() => {
    for (const player of world.getPlayers()) {
        applyEnchantScoreboards(player);
        setBookLore(player);
    }
}, 30);

// If switching slot we should instantly apply the new enchants
system.runInterval(() => {
    for (const player of world.getPlayers()) {
        let equippedItemTypeId = player.getComponent('equippable').getEquipment('Mainhand');
        if (equippedItemTypeId) {
            equippedItemTypeId = equippedItemTypeId.typeId;
        } else {
            equippedItemTypeId = "minecraft:air";
        }
        const newSlot = player.selectedSlotIndex !== player.getDynamicProperty("cubc_mo_en:selected_slot");
        const newItem = equippedItemTypeId !== player.getDynamicProperty("cubc_mo_en:selected_item");
        if (newSlot || newItem) {
            applyEnchantScoreboards(player);
            setBookLore(player);
            player.setDynamicProperty("cubc_mo_en:selected_slot", player.selectedSlotIndex);
            player.setDynamicProperty("cubc_mo_en:selected_item", equippedItemTypeId);
        }
    }
}, 1);
