import { ItemComponentTypes, system, world } from "@minecraft/server";
import { SuppItems } from "../reg/suppItems";
import { damageItemIfInSurvival, getItemInHand, setItemInMainHand } from "../util/miscUtils";
const usingBlower = new Map();
world.beforeEvents.itemUse.subscribe((event) => {
    const item = event.itemStack.typeId;
    usingBlower.delete(event.source); // Clear previous usage time
    if (item == SuppItems.BubbleBlower) {
        const damage = event.itemStack.getComponent(ItemComponentTypes.Durability);
        if (damage.damage >= damage.maxDurability) {
            event.cancel = true;
            return;
        }
        usingBlower.set(event.source, 0);
        system.run(() => {
            const player = event.source;
            player.playAnimation("animation.razz_sup.player.third_person.use_bubble_blower", { stopExpression: "!query.is_using_item", blendOutTime: 0 });
        });
    }
});
function onFinishUse(event) {
    const itemStack = event.itemStack;
    if (itemStack && itemStack.typeId == SuppItems.BubbleBlower) {
        const player = event.source;
        const usedFor = usingBlower.get(player);
        if (usedFor) {
            const damage = calculateDamage(usedFor);
            damageItemIfInSurvival(player, event.itemStack, damage, false);
            usingBlower.delete(player);
        }
    }
}
world.afterEvents.itemStopUse.subscribe((event) => {
    onFinishUse(event);
});
function calculateDamage(time) {
    return Math.max(Math.floor(time / 4), 1);
}
system.runInterval(() => {
    for (const [player, time] of usingBlower.entries()) {
        if (!player || !player.isValid) {
            usingBlower.delete(player);
            continue;
        }
        const item = getItemInHand(player);
        if (!item)
            return;
        const durabilityLost = calculateDamage(time);
        const itemDamage = item.getComponent(ItemComponentTypes.Durability);
        if (itemDamage.damage + durabilityLost >= itemDamage.maxDurability) {
            //stop using item
            const p = player;
            setItemInMainHand(p, undefined);
            setItemInMainHand(p, item);
            damageItemIfInSurvival(player, item, itemDamage.maxDurability, false);
        }
        usingBlower.set(player, time + 1);
    }
});
