import { world, system, EntityComponentTypes, } from "@minecraft/server";
import { addVector3, randomVector3 } from "util/vector3Functions";
export const enderTeleport = (target, dist, chance, delay) => {
    if (Math.random() > chance) {
        return;
    }
    const health = target.getComponent(EntityComponentTypes.Health);
    if (!!health && health.currentValue <= 0) {
        return;
    }
    const dimension = world.getDimension(target.dimension.id);
    if (!dimension) {
        return;
    }
    system.runTimeout(() => {
        let pos = null;
        let foundValidLocation = false;
        let baseLocation = target.typeId !== "minecraft:ender_dragon"
            ? target.location
            : { x: 0, y: 64, z: 0 };
        for (let i = 0; i < 3; i++) {
            pos = addVector3(baseLocation, randomVector3(dist));
            if (target.typeId === "minecraft:ender_dragon") {
                pos.y = Math.min(Math.max(pos.y, 200), 64);
            }
            if (pos.y < dimension.heightRange.min ||
                pos.y > dimension.heightRange.max) {
                continue;
            }
            if (dimension.getBlock(pos) && dimension.getBlock(pos).isAir) {
                foundValidLocation = true;
                break;
            }
        }
        if (!foundValidLocation) {
            return;
        }
        const volume = target.typeId === "minecraft:ender_dragon" ? 25.0 : 2.0;
        world.playSound("mob.endermen.portal", target.location, {
            volume: volume,
        });
        for (let i = 0; i < 50; i++) {
            dimension.spawnParticle("minecraft:end_chest", addVector3(target.location, randomVector3(2)));
        }
        target.teleport(pos);
        if (target.typeId == "minecraft:ender_dragon") {
            target.triggerEvent("minecraft:start_fly");
        }
        world.playSound("mob.endermen.portal", pos, {
            volume: volume,
        });
        for (let i = 0; i < 50; i++) {
            dimension.spawnParticle("minecraft:end_chest", addVector3(pos, randomVector3(2)));
        }
    }, delay ?? 0);
};
