import * as mc from "@minecraft/server";
import * as utils from "../utils/index";
import { ignoreEntities } from "../shared/constants";
const tickDuration = 22;
const down = { x: 0, y: -1, z: 0 };
export function pigsAbility(player) {
    utils.mclog(`Pigs`);
    const victims = player.dimension.getEntities({ location: player.location, maxDistance: 10, excludeTypes: ignoreEntities, excludeNames: [player.nameTag], excludeTags: ['friendlyFireOff'] });
    if (victims.length) {
        const endTime = mc.system.currentTick + tickDuration;
        for (const victim of victims) {
            spawnAxe(endTime, victim, player);
        }
    }
    else {
        const direction = new utils.Vector3({ x: player.getViewDirection().x, y: 0, z: player.getViewDirection().z });
        const origin = new utils.Vector3(player.getHeadLocation()).add(direction.multiply(3));
        const block = player.dimension.getBlockFromRay(origin, down, { includeLiquidBlocks: false, includePassableBlocks: false, maxDistance: 5 });
        let target = new utils.Vector3(player.location).add(direction.multiply(3));
        if (block) {
            target = new utils.Vector3(block.block.location).add(new utils.Vector3(block.faceLocation));
        }
        mc.world.playSound('ability.pig.squeal', target);
        player.dimension.spawnEntity('ldz:pig_ability_axe', target);
    }
}
async function spawnAxe(endTime, victim, player) {
    if (victim.isValid()) {
        mc.world.playSound('ability.pig.squeal', victim.location);
        const axe = victim.dimension.spawnEntity('ldz:pig_ability_axe', victim.location);
        await utils.waitForLoopEvent(0, () => {
            if (victim.isValid() && axe.isValid()) {
                axe.teleport(victim.location);
            }
            return mc.system.currentTick >= endTime;
        });
        if (victim.isValid()) {
            victim.applyDamage(5, { damagingEntity: player.UnsafeEntity, cause: mc.EntityDamageCause.entityAttack });
        }
    }
}
