import { Player, system, world } from "@minecraft/server";

world.afterEvents.itemCompleteUse.subscribe((event) => {
    const { source, itemStack, useDuration } = event;
    if (!(source instanceof Player)) return;

    if (itemStack.hasTag('oct_db:rotten_food')) {
        const player = source;
        const tags = itemStack.getTags();

        // Poisonous Food
        if (tags.includes('oct_db:poisonous_food')) {
            // Chicken
            if (tags.includes('oct_db:chicken')) {
                const percentChance = 0.75;
                if (Math.random() < percentChance) {
                    addPotionEffect(player, "minecraft:nausea", 20, 1);
                    addPotionEffect(player, "minecraft:hunger", 30, 2);
                } else {
                    addPotionEffect(player, "minecraft:hunger", 30, 1);
                };
            }
            // Potato
            if (tags.includes('oct_db:poisonous_potato')) {
                addPotionEffect(player, "minecraft:poison", 10, 2);
            }
            // Pufferfish
            if (tags.includes('oct_db:pufferfish')) {
                addPotionEffect(player, "minecraft:nausea", 30, 1);
                addPotionEffect(player, "minecraft:poison", 90, 1);
                addPotionEffect(player, "minecraft:hunger", 30, 2);
            }
        }
        // Normal Rotten Food 
        else {
            addPotionEffect(player, "minecraft:poison", 10, 0, 0.1);
            addPotionEffect(player, "minecraft:nausea", 10, 0, 0.5);
            addPotionEffect(player, "minecraft:hunger", 30, 1);
        }

        // world.sendMessage(
        //     `Player ${player.name} completed use of item (${itemStack.typeId})`
        // );
    };

});

/**
 * Adds a potion effect to the player
 * @param {Player} player The player to add the effect to
 * @param {string} effect The effect to add
 * @param {number} duration The duration of the effect in seconds
 * @param {number} amplifier The amplifier of the effect (default 1)
 * @param {number} percentChance The chance for the effect to be added (default 1 = 100%)
 */
function addPotionEffect(player, effect, duration, amplifier = 0, percentChance = 1) {
    if (Math.random() > percentChance) return;

    const timeInTicks = duration * 20;
    player.addEffect(
        effect,
        timeInTicks,
        {
            amplifier: amplifier,
            showParticles: true
        }
    );

}