import * as mc from "@minecraft/server";
import * as vector from "../utils/vector";
import * as selectors from "../utils/selectors";

export function eventBehavior(event) {
    const entity = event.entity;

    if (event.eventId === "spawned_naturally") {
        const animals = selectors.union({
            location: entity.location,
            maxDistance: 6,
        }, ["pig", "sheep", "cow", "chicken"], entity.dimension, entity.id);
        if (animals[0] !== undefined) {
            entity.remove();
            return;
        }

        const blockDown = entity.dimension.getBlock(vector.add(entity.location, {x:0, y:-1.5, z:0}));
        if (blockDown.typeId !== "minecraft:grass_block" && blockDown.typeId !== "minecraft:dirt")
            entity.remove()
        return;
    }
    // make it despawn because very rarely it fails to for some reason
    if (event.eventId === 'death') {
        mc.system.runTimeout(()=>{
            if (!event.entity.isValid())
                return;
            event.entity.triggerEvent("drop");
        }, 45);
        return;
    }
}

export function hitBehavior(event) {
    if (!event.hitEntity.isValid()) 
        return;
    const dir = vector.subtract(event.hitEntity.location, event.damagingEntity.location);
    const force = 3/vector.magnitude(dir);
    event.hitEntity.applyKnockback(dir.x, dir.z, force, 0.35);

    if (event.hitEntity.getComponent('health')?.currentValue === 0) {
        event.damagingEntity.addEffect("regeneration", 60, {
            amplifier: 2,
            showParticles: true
        });
    }
    //mc.world.sendMessage(`${event.hitEntity.getComponent('health').currentValue}`);
}