import * as mc from "@minecraft/server";
import { SafetyCheckedEntity, SafetyCheckedPlayer, Vector3, waitForLoopEvent } from "./utils/index";
import { EntityFamilyChecker } from "./utils/entity_family_checker";
export function initArmadilloWeapon() {
    mc.system.afterEvents.scriptEventReceive.subscribe(event => {
        if (event.id === "ldz:armadillo_weapon" && event.sourceEntity && event.sourceEntity.typeId === "minecraft:player") {
            armadilloWeapon(new SafetyCheckedPlayer(event.sourceEntity));
        }
    });
}
function armadilloWeapon(player) {
    const playerYRotation = player.getRotation().y;
    const spawnLocation = player.location.add(Vector3.SOUTH.multiply(0.6).rotateByAngle(playerYRotation).add(Vector3.UP.multiply(0.9)));
    player.runCommand("playsound mob.armadillo_weapon_projectile.shoot @a ~ ~ ~");
    for (let index = -1; index <= 1; index++) {
        let rotation = playerYRotation;
        rotation += index * 15;
        spawnArmadillo(player.dimension, spawnLocation, rotation, player);
    }
}
function spawnArmadillo(dimension, location, rotation, owner) {
    const armadillo = new SafetyCheckedEntity(dimension.spawnEntity("ldz:armadillo_weapon_projectile", location));
    armadillo.setRotation({ x: 0, y: rotation });
    const moveDirection = Vector3.SOUTH.rotateByAngle(rotation);
    armadillo.applyImpulse(moveDirection.multiply(0.5));
    waitForLoopEvent(1, () => {
        if (armadillo.isValid()) {
            rollArmadillo(armadillo, owner);
            return false;
        }
        else {
            return true;
        }
    });
}
function rollArmadillo(armadillo, playerOwner) {
    const moveDirection = Vector3.SOUTH.rotateByAngle(armadillo.getRotation().y);
    if (armadillo.isOnGround) {
        armadillo.applyImpulse(moveDirection.multiply(0.25));
    }
    else {
        armadillo.applyImpulse(moveDirection.multiply(0.05));
    }
    armadillo.dimension.getEntities({ location: armadillo.location, maxDistance: 0.75 })
        .map(entity => new SafetyCheckedEntity(entity))
        .filter(entity => entity.id !== armadillo.id && entity.id !== playerOwner.id)
        .filter(entity => EntityFamilyChecker.hasAnyFamily(entity, "aggronaut", "captain", "monster", "mob", "animal", "fish"))
        .forEach(entity => {
        armadillo.runCommand("playsound mob.armadillo_weapon_projectile.hit_entity @a ~ ~ ~");
        const direction = entity.location.subtract(armadillo.location).normalize();
        entity.applyImpulse(direction.multiply(0.5));
        entity.applyDamage(2, { cause: mc.EntityDamageCause.entityAttack, damagingEntity: (playerOwner.isValid() ? playerOwner.UnsafeEntity : armadillo.UnsafeEntity) });
    });
}
