import { EntityHealthComponent, system, world } from "@minecraft/server";
import functions from './lib/functions';

const protectedPlayers = new Map();

system.runInterval(async () => {
    for (const player of world.getPlayers()) {
        const weapon = functions.findWeapon(player);

        if (functions.getWeapon(player, true)?.typeId == "minecraft:shield") continue;
        if (!(weapon && player.isSneaking)) {
            protectedPlayers.delete(player.nameTag);
            continue
        } else if (!protectedPlayers.get(player.nameTag)) protectedPlayers.set(player.nameTag, weapon);
        player.addEffect("weakness", 20, { amplifier: 5, showParticles: false });
        player.playAnimation("animation.player.weapon_blocking");
    }
});

world.afterEvents.entityHurt.subscribe(event => {
    const { hurtEntity: player, damage, damageSource: source } = event;
    const { damagingEntity:  entity, damagingProjectile: projectile } = source;
    const protectedPlayer = protectedPlayers.get(player.nameTag);

    if (!protectedPlayer) return;
    const healthComponent = player.getComponent(EntityHealthComponent.componentId);
    const reduction = functions.calculateReduction(damage, entity || projectile, !!projectile);

    player.playSound('item.shield.block');
    functions.damageWeapon(player, protectedPlayer);
    player.teleport(player.location);
    system.run(() => {
        healthComponent.setCurrentValue(healthComponent.currentValue + reduction);
    });
}, { entityTypes: [ "minecraft:player" ] });


system.beforeEvents.watchdogTerminate.subscribe(ev => ev.cancel = true);