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

export function eventBehavior(event) {
    if (event.eventId === "register") {
        event.entity.setProperty('hf_mzs:pump', false);
    }
    // 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");
        }, 3);
        return;
    }
}
export function tick5(entity) {
    const ground = entity.dimension.getBlockFromRay(entity.location, vector.down, {
        maxDistance: 500,
        includePassableBlocks: true,
        includeLiquidBlocks: true,
    });
    if (ground === undefined || !ground.block.isValid())
        return;

    const h = Math.abs(entity.location.y-ground.block.location.y);
    if ((h <= 5 || (Math.random()<=0.26 && h <= 16)) && !entity.getProperty('hf_mzs:pump')) {
        pump(entity);
    }
    //if (!entity.getDynamicProperty('hf_mzs:moving_up'))
}

function pump(entity) {
    entity.setProperty('hf_mzs:pump', true);
    mc.system.runTimeout(()=>{
        if (!entity.isValid())
            return;
        entity.clearVelocity();
        const force = { 
            x: (Math.random()-0.5)*0.7, 
            y: 0.27, 
            z: (Math.random()-0.5)*0.7 
        };
        entity.applyImpulse(force);
        mc.system.runTimeout(()=>{
            if (!entity.isValid())
                return;
            entity.applyImpulse(vector.multiply(vector.up, -0.295));
        }, 10);
        mc.system.runTimeout(()=>{
            if (!entity.isValid())
                return;
            entity.setProperty('hf_mzs:pump', false);
        }, 40+Math.random()*30);
    }, 6);
}