import { world, system, Entity, EntityComponentTypes, ItemStack, EquipmentSlot } from "@minecraft/server"
import { openUpgradeMenu } from "../forms/gauntletMenu";


world.afterEvents.playerInteractWithEntity.subscribe(e => {
    const p = e.player;
    const item = e.itemStack;
    const upgrader = e.target;
    const has_gauntlet = upgrader.getProperty('oct_eg:element') != 0;

    if (upgrader.typeId != "oct_eg:gauntlet_upgrader") return;

    //place the gauntlet on it
    if (item && item.typeId.includes("oct_eg") && item.typeId.includes("_gauntlet")) {
        const element = item?.typeId.split("oct_eg:")[1].replace("_gauntlet", "");
        //prevent the player from placing another gauntlet without removing the current one
        if (has_gauntlet) return;

        //remove the gauntlet from the player's hand
        p.getComponent("minecraft:equippable").getEquipmentSlot(EquipmentSlot.Mainhand).setItem(undefined);
        //store the gauntlet using DP to preserve durability
        storeGauntletItem(item, upgrader);

        //change the table variant and render the icon
        upgrader.triggerEvent("oct_eg:element." + element);

        //open the menu
        const timer = system.runTimeout(() => {
            openUpgradeMenu(p, "oct_eg:" + element + "_gauntlet");
        }, 10)

        //store the timer to cancel it if the player removes the gauntlet before the menu opens
        upgrader.setDynamicProperty("oct_eg:upgrader.timer", timer);

    } else //remove the gauntlet from it if the player isn't holding any gauntlet and there's a gauntlet on the upgrader)
        if (!item && has_gauntlet) {

            //prevent the menu from opening when the gauntlet is removed
            if (upgrader.getDynamicProperty("oct_eg:upgrader.timer"))
                system.clearRun(upgrader.getDynamicProperty("oct_eg:upgrader.timer"));

            const stored_gauntlet = restoreItem(upgrader);
            upgrader.dimension.spawnItem(stored_gauntlet, upgrader.location);
            upgrader.triggerEvent("oct_eg:element.default");
        }
})


system.afterEvents.scriptEventReceive.subscribe(e => {
    if (!(e.id == "oct_eg:gauntlet_upgrader" && e.message == "update_gauntlet_crafter")) return;

    const table = e.sourceEntity.dimension.getBlock(e.sourceEntity.location).below();
    const element = e.sourceEntity.getProperty('oct_eg:element');

    table.setPermutation(table.permutation.withState("oct_eg:element", element));
});


function storeGauntletItem(item, table) {
    const data = {
        type: item.typeId,
        durability: item.getComponent("minecraft:durability").damage,
        nameTag: item.nameTag
    }
    table.setDynamicProperty("oct_eg:gauntlet_on_table", JSON.stringify(data));
}


function restoreItem(table) {
    const data = JSON.parse(table.getDynamicProperty("oct_eg:gauntlet_on_table"));
    const item = new ItemStack(data.type, 1);
    item.nameTag = data.nameTag;
    item.getComponent("minecraft:durability").damage = data.durability;
    return item;
}

export function onRemoveUpgrader(upgrader) {
    try {
        //world.sendMessage(`§cGauntlet Upgrader §2removed§r`);

        const has_gauntlet = upgrader.getProperty('oct_eg:element') != 0;

        if (has_gauntlet) {
            const stored_gauntlet = restoreItem(upgrader);
            upgrader.dimension.spawnItem(stored_gauntlet, upgrader.location);
        }

        upgrader.remove();
    }
    catch (e) {
        upgrader?.remove();
        world.sendMessage(e);
    }
}