import * as mc from "@minecraft/server";
import * as utils from "../utils/index";
import { preventFallDamage } from '../local_utils';
export function onSlimeUse(player) {
    utils.mclog(`${player.nameTag} Used Slime Weapon`);
    if (player.isFlying) {
        player.onScreenDisplay.setActionBar({ rawtext: [{ translate: "action.hint.warn.ldz_240409:weapon_slime" }] });
    }
    if (!player.isOnGround)
        return;
    utils.modifyEquipmentDurability(player, mc.EquipmentSlot.Mainhand, -1);
    mc.world.playSound('ldz_240409:player.slime_weapon.jump', player.location);
    player.applyKnockback(0, 0, 0, 1);
    preventFallDamage(player, { startDelayTicks: 2 });
    utils.waitForEvent(3, () => onBounce(player));
}
async function onBounce(player) {
    let falling = false;
    const risingTicksThreshold = 2;
    let risingTicks = 0;
    let snuck = false;
    utils.waitForLoopEvent(0, () => {
        if (player.isSneaking && !snuck) {
            snuck = true;
            player.applyKnockback(0, 0, 0, -3);
        }
        if (snuck)
            player.addEffect("slow_falling", 5, { showParticles: false });
        if (snuck && player.isOnGround) {
            player.dimension.spawnParticle("ldz_240409:ground_slam", player.location);
            player.dimension.spawnParticle("ldz_240409:slime_impact", player.location);
            mc.world.playSound('ldz_240409:player.slime_weapon.impact', player.location);
            mc.world.playSound('ldz_240409:player.slime_weapon.land', player.location);
            const playerHeight = player.location.y;
            utils.getEntitiesSafe(player.dimension, { location: player.location, maxDistance: 10 }).forEach(victim => {
                if (victim.id === player.id)
                    return;
                const victimHeight = victim.location.y;
                if (Math.abs(playerHeight - victimHeight) > 1.1)
                    return;
                try {
                    const direction = victim.location.subtract(player.location).normalize();
                    const magnitude = (10 - player.location.distance(victim.location)) * 0.1;
                    victim.applyKnockback(direction.x, direction.z, magnitude * 1.5, magnitude);
                    victim.applyDamage(6, { cause: mc.EntityDamageCause.entityAttack, damagingEntity: player.UnsafeEntity });
                }
                catch (error) {
                    utils.mcwarn(`Cannot Apply Damage To ${victim.typeId}`);
                }
            });
            return true;
        }
        const yVel = player.getVelocity().y;
        if (yVel <= 0)
            falling = true;
        if (yVel > 0 && falling)
            risingTicks++;
        return (falling && risingTicks >= risingTicksThreshold) || player.isOnGround;
    });
}
