import * as mc from '@minecraft/server';
import * as utils from './utils/index';
import { entityToPlayer, nearestEntityToLocation } from './local_utils';
const VALID_MOBS = [
    "armadillo",
    "bee",
    "blaze",
    "bogged",
    "breeze",
    "chicken",
    "cow",
    "creeper",
    "enderman",
    "ender_dragon",
    "evocation_illager",
    "frog",
    "ghast",
    "guardian",
    "iron_golem",
    "pig",
    "piglin",
    "pufferfish",
    "sheep",
    "skeleton",
    "slime",
    "spider",
    "villager_v2",
    "warden",
    "zombie",
];
export function initializeMobMagnet() {
    // Checks for players holding the mob magnet every other tick
    utils.waitForLoopEvent(1, () => {
        utils.getAllPlayersSafe().forEach(player => {
            checkMobMagnetInteraction(player);
        });
        return false;
    });
    // Listens for mob_magnet_interactor getting interacted with
    mc.system.afterEvents.scriptEventReceive.subscribe(event => {
        if (event.id === "ldz_240409:mob_magnet_interaction") {
            const punch = event.message === "punch";
            if (event.sourceEntity && event.sourceEntity.isValid()) {
                const player = entityToPlayer(event.sourceEntity);
                if (player)
                    doMobMagnetInteraction(player, punch);
            }
        }
    });
    // Detect usage even if no valid mobs are nearby
    mc.world.afterEvents.itemStartUse.subscribe(event => {
        if (event.itemStack.typeId === "ldz_240409:mob_magnet") {
            if (event.source && event.source.isValid()) {
                const player = entityToPlayer(event.source);
                if (player)
                    doMobMagnetInteraction(player, false);
            }
        }
    });
}
function checkMobMagnetInteraction(player) {
    let playerEquipment = player.Equipment;
    let heldItem = playerEquipment === null || playerEquipment === void 0 ? void 0 : playerEquipment.getEquipment(mc.EquipmentSlot.Mainhand);
    if ((heldItem === null || heldItem === void 0 ? void 0 : heldItem.typeId) === "ldz_240409:mob_magnet") {
        const inFront = getEntitiesInFront(player);
        const validInFront = inFront.filter(entity => VALID_MOBS.includes(entity.typeId.replace("minecraft:", "")));
        if (validInFront.length > 0) {
            if (!player.runCommand("execute positioned ~ ~1.6 ~ positioned ^ ^ ^1 run testfor @e[type=ldz_240409:mob_magnet_interactor,r=1]").successCount) {
                player.runCommand("execute positioned ~ ~1.6 ~ run summon ldz_240409:mob_magnet_interactor ^ ^ ^1");
            }
            player.runCommand("execute positioned ~ ~1.6 ~ positioned ^ ^ ^1 run event entity @e[type=ldz_240409:mob_magnet_interactor,r=1] reset_despawn_timer");
        }
    }
}
function doMobMagnetInteraction(player, punch) {
    let targetEntity;
    let lookingAt = player.getEntitiesFromViewDirection({ maxDistance: 6 });
    const lookingAtGhast = player.getEntitiesFromViewDirection({ maxDistance: 30, type: "minecraft:ghast" });
    lookingAt = lookingAt.concat(lookingAtGhast);
    const validLookingAt = lookingAt.filter(entity => VALID_MOBS.includes(entity.entity.typeId.replace("minecraft:", "")));
    const inFront = getEntitiesInFront(player);
    const validInFront = inFront.filter(entity => VALID_MOBS.includes(entity.typeId.replace("minecraft:", "")));
    if (validLookingAt.length > 0) {
        utils.mclog("Target: Raycasted");
        targetEntity = validLookingAt[0].entity;
    }
    else {
        targetEntity = nearestEntityToLocation(player.location, validInFront);
        if (targetEntity) {
            utils.mclog("Target: Nearest");
        }
    }
    if (!targetEntity || !targetEntity.isValid()) {
        if (lookingAt.length > 0)
            targetEntity = lookingAt[0].entity;
        else
            targetEntity = nearestEntityToLocation(player.location, inFront);
        if (targetEntity) {
            targetEntity.runCommand(`particle ldz_240409:mob_magnet_fail ~ ~ ~`);
            targetEntity.runCommand(`playsound ldz_240409:player.mob_magnet.fail @a ~ ~ ~`);
            utils.mclog("Target: Invalid");
        }
        else {
            utils.mclog("Target: None");
        }
        return;
    }
    if (!punch) {
        const loc = new utils.Vector3(targetEntity.location);
        targetEntity.runCommand(`loot spawn ${loc} loot "ldz/240409/genes_${targetEntity.typeId.replace("minecraft:", "")}"`);
        if (targetEntity.typeId !== "minecraft:ghast")
            targetEntity.runCommand(`playsound ldz_240409:player.mob_magnet.use @a ~ ~ ~`);
        else
            targetEntity.runCommand(`playsound ldz_240409:player.mob_magnet.use @a ~ ~ ~ 5`);
        if (player.matches({ excludeGameModes: [mc.GameMode.creative] })) {
            utils.modifyEquipmentDurability(new utils.SafetyCheckedEntity(player), mc.EquipmentSlot.Mainhand, -1);
        }
    }
    else {
        targetEntity.applyDamage(1, { damagingEntity: player.UnsafeEntity, cause: mc.EntityDamageCause.entityAttack });
    }
}
function getEntitiesInFront(entity) {
    entity.runCommand("tag @s add self");
    entity.runCommand("execute positioned ^ ^ ^0 run tag @e[r=1,tag=!self] add ldz_240409:view_target");
    entity.runCommand("execute positioned ^ ^ ^1 run tag @e[r=2,tag=!self] add ldz_240409:view_target");
    entity.runCommand("execute positioned ^ ^ ^2 run tag @e[r=3,tag=!self] add ldz_240409:view_target");
    const inFront = utils.getEntitiesSafe(entity.dimension, { tags: ["ldz_240409:view_target"] });
    entity.runCommand("tag @s remove self");
    entity.runCommand("tag @e[tag=ldz_240409:view_target] remove ldz_240409:view_target");
    return inFront;
}
