import { EntityHealthComponent, system, world } from "@minecraft/server";
import { getRandomItem } from "../../functions";

const fractureTimers = new Map();
const messages = [
    "trueweapons.broken_bone.line1",
    "trueweapons.broken_bone.line2",
    "trueweapons.broken_bone.line3",
    "trueweapons.broken_bone.line4",
    "trueweapons.broken_bone.line5"
];

export default {
    async execute(player, item) {
        const tag = item.getTags()?.find(tag => tag == "fracture");

        if (!tag) return;
        if (Math.random() > (5 / 100)) return;
        player.onScreenDisplay.setActionBar({ translate: getRandomItem(messages) });
        player.playSound("true.player.dismembered", { pitch: 1.5 });
        fractureTimers.set(player.id, 180 * 20);
    }
}

system.runInterval(() => {
    for (const playerId of fractureTimers.keys()) {
        const player = world.getEntity(playerId);
        
        if (!player) continue;
        const playerHealthComponent = player.getComponent(EntityHealthComponent.componentId);

        if (fractureTimers.get(playerId) <= 0) {
            fractureTimers.delete(playerId);
            continue;
        }
        if (playerHealthComponent.currentValue >= 18) playerHealthComponent.setCurrentValue(18);
        fractureTimers.set(playerId, fractureTimers.get(playerId) - 1);
    }
}, 0);