import { world, system } from "@minecraft/server";
import { dropBuddyParts, checkBuddyProperties } from "./getBuddyPart";

const lizardRegenDelay = new Map();
const hermitCrabRegenDelay = new Map();

world.afterEvents.entityHitEntity.subscribe((data) => {
  const attacked = data.hitEntity;
  const damager = data.damagingEntity;

  if (attacked.typeId == "arcedge_bap:buddy_builder") {
    attacked.triggerEvent("arcedge_bap:despawn_buddy_builder");
    dropBuddyParts(attacked)
  }

  if(attacked.typeId == "arcedge_bap:buddy" && checkBuddyProperties(8, attacked)) {
    const buddyId = attacked.id;

    if (lizardRegenDelay.has(buddyId)) {
      system.clearRun(lizardRegenDelay.get(buddyId));
      lizardRegenDelay.delete(buddyId);
    }

     const timeoutId = system.runTimeout(() => {
      try {
        attacked.addEffect("regeneration", 60, { amplifier: 255, showParticles: false });
      }
      catch {}
      finally {
        lizardRegenDelay.delete(attacked.id);
      }
    }, 400);

    lizardRegenDelay.set(attacked.id, timeoutId);
  }

 if (attacked.typeId == "arcedge_bap:buddy" && checkBuddyProperties(6, attacked)) {
    const buddyId = attacked.id;

    if (hermitCrabRegenDelay.has(buddyId)) {
      system.clearRun(hermitCrabRegenDelay.get(buddyId));
      hermitCrabRegenDelay.delete(buddyId);
    }

    try {
      const currentShell = attacked.getProperty("arcedge_bap:hermit_crab_shell_size") ?? 5;
      const newShell = Math.max(currentShell - 1, 0);
      attacked.setProperty("arcedge_bap:hermit_crab_shell_size", newShell);

      const timeoutId = system.runTimeout(function shellRegenLoop() {
        try {
          const shellNow = attacked.getProperty("arcedge_bap:hermit_crab_shell_size") ?? 0;
          if (shellNow < 5) {
            attacked.setProperty("arcedge_bap:hermit_crab_shell_size", shellNow + 1);

            hermitCrabRegenDelay.set(
              buddyId,
              system.runTimeout(shellRegenLoop, 150)
            );
          } else {
            hermitCrabRegenDelay.delete(buddyId);
          }
        } catch {
          hermitCrabRegenDelay.delete(buddyId);
        }
      }, 150);

      hermitCrabRegenDelay.set(buddyId, timeoutId);
    } catch {}
  }

  if(damager.typeId == "arcedge_bap:buddy" && checkBuddyProperties(5, damager)) {
    if(attacked.getComponent('minecraft:type_family')?.hasTypeFamily('zombie')) return attacked.addEffect("instant_health", 100, { amplifier: 1, showParticles: true });
    attacked.addEffect("poison", 100, { amplifier: 1, showParticles: true });
  }
});

export function roarAttack(buddy, buddyType) {
  buddy.addEffect("slowness", 20, { amplifier: 255, showParticles: false });
  buddy.playAnimation("animation.arcedge_bap_buddy_" + buddyType + ".roar")
}
