import * as server from "@minecraft/server";

server.world.afterEvents.itemCompleteUse.subscribe(result => {

    let itemStack = result.itemStack;

    const badEffects = ["bad_omen", "blindness", "fatal_poison", "hunger", "instant_damage", "mining_fatigue", "nausea", "poison", "slowness", "weakness", "wither", "darkness"]
    const allEffects = server.EffectTypes.getAll().map(effect => effect.getName());
    let items = [
        { effect: "regeneration", duration: 5, amplifier: 0, itemTypeId: "farmersdelight:fruit_salad" },
        { effect: "regeneration", duration: 5, amplifier: 0, itemTypeId: "farmersdelight:mixed_salad" },
        { effect: "nausea", weight: 20, duration: 10, amplifier: 0, itemTypeId: "farmersdelight:nether_salad" },
        { effect: "hunger", weight: 30, duration: 10, amplifier: 0, itemTypeId: "farmersdelight:chicken_cuts" },
        { effect: "absorption", duration: 60, amplifier: 0, itemTypeId: "farmersdelight:apple_cider" },
        { effect: "night_vision", duration: 30, amplifier: 0, itemTypeId: "farmersdelight:glow_berry_custard" },
        { effect: badEffects, remove: true, itemTypeId: "farmersdelight:hot_cocoa" },
        { effect: allEffects, remove: true, itemTypeId: "farmersdelight:milk_bottle" },
        { effect: "hunger", weight: 20, duration: 30, amplifier: 0, itemTypeId: "farmersdelight:raw_pasta" },
        { effect: "hunger", weight: 20, duration: 30, amplifier: 0, itemTypeId: "farmersdelight:wheat_dough" },
        { effect: "instant_health", duration: 0.05, amplifier: 0, itemTypeId: "farmersdelight:melon_juice" }
    ];
    for (let item of items) {
        if (itemStack.typeId === item.itemTypeId) {
            let effect = item.effect;
            let duration = item.duration;
            let amplifier = item.amplifier;

            if (item.weight) {
                let weight = item.weight;
                let random = Math.random() * 100;
                if (random < weight) {
                    result.source.addEffect(effect, duration * 20, { amplifier: amplifier });
                }
            } else {
                if (!item.remove) result.source.addEffect(effect, duration * 20, { amplifier: amplifier });
            }

            if (item.remove) {
                item.effect.forEach(effect => {
                    result.source.removeEffect(effect);
                })
            }
        }
    }
});