import { EntityDamageCause, Player, world, Entity } from "@minecraft/server";
import { Entities } from "./Entities";
import { movePlayerAway } from "../utils/utils";

const difficultyDamage = new Map([
    [
        "easy",
        {
            damage: 4,
        },
    ],
    [
        "normal",
        {
            damage: 6,
        },
    ],
    [
        "hard",
        {
            damage: 8,
        },
    ],
]);

world.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
    const { entity, eventId } = event;

    if (entity.typeId == Entities.acrobat_juggler) {
        switch (eventId) {
            case "clown:knockup_attack": {
                knockupAttack(entity);

                break;
            }
            case "clown:move_player_away": {
                movePlayerAway(entity);

                break;
            }
        }
    }
});

/**
 *
 * @param {Entity} entity
 */
function knockupAttack(entity) {
    const nearbyEntities = entity.dimension.getEntities({
        location: entity.location,
        excludeTypes: ["minecraft:item", "minecraft:xp_orb"],
        maxDistance: 8,
    });

    const knockupVerticalPower = 1.2;

    const difficulty = entity.getProperty("clown:difficulty");

    const damage = difficultyDamage.get(difficulty).damage ?? 0;

    for (let mob of nearbyEntities) {
        if (mob != entity) {
            if (mob instanceof Player) {
                if (entity.matches({ excludeFamilies: ["passive"] })) {
                    mob.applyDamage(damage, {
                        cause: EntityDamageCause.entityAttack,
                        damagingEntity: entity,
                    });

                    mob.applyKnockback(0, 0, 0, knockupVerticalPower);
                }
            } else {
                mob.applyDamage(damage, {
                    cause: EntityDamageCause.entityAttack,
                    damagingEntity: entity,
                });

                mob.applyImpulse({ x: 0, y: knockupVerticalPower, z: 0 });
            }
        }
    }
}
