import { world, Player, EntityInventoryComponent, ItemStack } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { sendPlayerMessage, sendAllMessage, config } from "../../../config";
import { deadplayers, revivelist, getScore, getPlayer, addScore, setScore, gameruleSwitcheroo } from "../../../lifesteal";

world.afterEvents.itemUse.subscribe(({ itemStack: item, source }) => {
    let player = source as Player;
    if (getScore(player, `ls-death`) <= 1) return;

    if (item.typeId == `lifesteal:withdraw_heart`) {
        let withdrawGui = new ModalFormData()
            .title(`Withdraw Heart`)
            .slider(`How many hearts do you want to withdraw?`, 1, getScore(player, `ls-death`) - 1, 1);
        withdrawGui.show(player).then(({ canceled, cancelationReason, formValues }) => {
            if (canceled || !player.isValid()) return;

            if (getScore(player, `ls-death`) - +formValues[0] <= 0) {
                setScore(player, `ls-death`, 1);
            } else
                addScore(player, `ls-death`, -(+formValues[0]));

            let inventory = (player.getComponent(`inventory`) as EntityInventoryComponent)[`container`];
            let inventorySize = inventory.size;
            for (let i = 0; i < inventorySize; i++) {
                let item = inventory.getItem(i);
                if (!item || item.typeId !== `lifesteal:heart`) continue;
                inventory.setItem(i, new ItemStack(item.typeId, item.amount));
            }


            if (world.gameRules.sendCommandFeedback) {
                gameruleSwitcheroo(`sendCommandFeedback`, false);
            }
            player.runCommand(`give @s lifesteal:heart ${formValues[0]}`);
        });
    }
});