import { world, MolangVariableMap, system } from "@minecraft/server";


//add static to enemies
world.afterEvents.entityHurt.subscribe(e => {
    const pet = e.damageSource.damagingEntity;
    const hurt = e.hurtEntity;

    if (!(pet && hurt)) return;

    if (pet.typeId != "oct_eg:electro_pet") return;

    hurt.addStatic(1, 3);

    const endLocation = hurt.getHeadLocation();
    const startLocation = pet.getHeadLocation();
    const molang = new MolangVariableMap();

    molang.setFloat("offset_x", endLocation.x - startLocation.x);
    molang.setFloat("offset_y", endLocation.y - startLocation.y);
    molang.setFloat("offset_z", endLocation.z - startLocation.z);

    pet.dimension.spawnParticle("oct_eg:thunder_punch.bounce", startLocation, molang);
    pet.dimension.playSound("octovon.eg.gauntlet.electro.thunder_punch.zap", pet.location);
})

system.afterEvents.scriptEventReceive.subscribe((event) => {
    const pet = event.sourceEntity;
    if (event.id != "oct_eg:electro_pet") return;
    switch (event.message) {
        //gives speed to its owner
        case "speed_owner":
            const owner = pet.getComponent("minecraft:tameable").tamedToPlayer;

            owner?.addEffect("minecraft:speed", 5 * 20, { amplifier: 1, showParticles: false });
            pet.playAnimation("anim.pet.heal");
            pet.dimension.spawnParticle("oct_eg:discharge.entity_sparks", pet.location);
            pet.dimension.playSound("octovon.eg.gauntlet.electro.charged_dash", pet.location);
            addCooldown(pet);
            break;

        //checks if it's still on cooldown
        case "cooldown_check":
            if (!isOnCooldown(pet))
                pet.triggerEvent("oct_eg:speed_owner.true")
            break;
        default:
            break;
    }
});

/**
 * @param {Entity} pet
 */
function addCooldown(pet) {
    const currentTime = system.currentTick;
    const cooldown = 10 * 20;
    pet.setDynamicProperty("oct_eg:cooldown", currentTime + cooldown);
}

/**
 * @param {Entity} pet
 */
function isOnCooldown(pet) {
    return pet.getDynamicProperty("oct_eg:cooldown") > system.currentTick;
}