import * as mc from "@minecraft/server";
import * as utils from "../utils/index";
export async function end_portalAbility(player) {
    var _a;
    utils.mclog(`end_portal`);
    const monsters = utils.getEntitiesSafe(player.dimension, {
        location: player.location,
        families: ["monster"],
        maxDistance: 16,
    });
    mc.world.playSound('ability.end_portal.activate', player.location);
    if (!monsters.length) {
        const origin = player.getHeadLocation().add(player.getViewDirection().multiply(3));
        const block = player.dimension.getTopmostBlock(origin, origin.y + 5);
        const portal = utils.spawnEntitySafe(player.dimension, "ldz:end_portal_ability", new utils.Vector3((_a = block === null || block === void 0 ? void 0 : block.location) !== null && _a !== void 0 ? _a : origin).center().up(3));
        utils.waitForEvent(1.5 * mc.TicksPerSecond, () => {
            if (portal.isValid()) {
                portal.remove();
            }
        });
        return;
    }
    for (const monster of monsters) {
        monster.teleport(monster.location.center());
        monster.addEffect("minecraft:slowness", 1.5 * mc.TicksPerSecond, { amplifier: 255, showParticles: false });
        const portal = utils.spawnEntitySafe(monster.dimension, "ldz:end_portal_ability", monster.location.up(2));
        utils.waitForEvent(0.6 * mc.TicksPerSecond, () => {
            if (monster.isValid()) {
                lockInPlace(monster, monster.location.down());
                monster.applyDamage(10, { cause: mc.EntityDamageCause.entityAttack, damagingEntity: player.UnsafeEntity });
            }
        });
        utils.waitForEvent(1.5 * mc.TicksPerSecond, () => {
            if (portal.isValid()) {
                portal.remove();
            }
        });
    }
}
async function lockInPlace(monster, position) {
    for (let index = 0; index < 20; index++) {
        if (!monster.isValid())
            return;
        monster.teleport(position);
        await utils.waitForTicks(0);
    }
}
