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

const bleedingEntites = new Map();
const BLEEDING_REGEXP = /sharp:[0-9]+:[0-9]+:[0-9]+/;
const messages = [
    "trueweapons.bleeding.line1",
    "trueweapons.bleeding.line2",
    "trueweapons.bleeding.line3",
    "trueweapons.bleeding.line4"
];

export default {
    async execute(itemStack, damagedEntity) {
        const bleedingTag = hasTag(itemStack, null, BLEEDING_REGEXP);
        const [ _damage, duration, probability ] = this.getBleedingParameters(bleedingTag);
        let damage = _damage;

        if (!bleedingTag || bleedingEntites.has(damagedEntity.id)) return;
        if (Math.random() > (probability / 100)) return;
        if (damagedEntity.typeId == "minecraft:player") damagedEntity.onScreenDisplay.setActionBar({ translate: getRandomItem(messages) });
        const enchantments = itemStack.getComponent("minecraft:enchantable");

        if (enchantments) {
            const sharpnessEnchantment = enchantments.getEnchantment("sharpness");

            if (!sharpnessEnchantment) return; 
            damage += sharpnessEnchantment.level * 1.25;
        }
        console.warn(damage)
        bleedingEntites.set(damagedEntity.id, { 
            damagedEntityId: damagedEntity.id,
            damage,
            duration: duration * 20
        });
    },
    getBleedingParameters(bleedingTag) {
        if (!bleedingTag) return [];
        return bleedingTag
            .split(":")
            .slice(1)
            .map(Number);
    }
}

system.runInterval(() => { 
    for (const [ bleedingDataID, bleedingData ] of bleedingEntites.entries()) {
        const { damagedEntityId, damage, duration } = bleedingData;
        const damagedEntity = world.getEntity(damagedEntityId);
       
        if (!damagedEntity) {
            bleedingEntites.delete(bleedingDataID);
            continue;    
        }
        if ((duration - 20) > 0) {
            bleedingData.duration -= 20;

            if (damagedEntity.typeId == "minecraft:player" && (!damagedEntity.isSprinting && damagedEntity.isSneaking)) continue;
            
            damagedEntity.applyDamage(damage);
            damagedEntity.runCommandAsync("particle minecraft:lava_drip_particle ~ ~ ~");
            continue;
        }
        bleedingEntites.delete(bleedingDataID);
    }
}, 20);
