import * as mc from "@minecraft/server";
import { random } from "../lib";
import { difficultyDamageController } from './index'

// Delays personalizados (em ticks)
const deathDelays = {
  fire_elemental: 2,
  water_elemental: 2,
  earth_elemental: 2,
  air_elemental: 2,
  spirit_elemental: 2,
  steel_behemont: 2,
  void_monster: 2,
  magma_warden: 2,
  electricity_elemental: 2,
  glacier_colossus: 2
};

mc.world.afterEvents.entityHurt.subscribe(data => {
  const e = data.hurtEntity;
  if (!e.dimension.getEntities({ location: e.location, maxDistance: 1, families: ["ld_eb_elemental"] })
        .some(ent => ent.id === e.id)) return;

  if (!mc.world.getDynamicProperty("ld_eb:efeitos_sonoros")) return;
  /** @type {mc.EntityHealthComponent} */
  const entityHealth = e.getComponent(mc.EntityHealthComponent.componentId);
  if (entityHealth.currentValue <= 1) return;

  let id = getId(e);
  id === "steel_behemoth" ? id = "steel_behemont" : null
  mc.world.playSound(`ld_eb.${id}.hurt`, e.location, { pitch: random(9, 11) / 10, volume: 20 });
});

mc.system.afterEvents.scriptEventReceive.subscribe(async data => {
  const e = data.sourceEntity;
  if (data.id !== "ld_eb:death") return;

  //EXP
  {
    for (let index = 0; index < 13; index++) {
      e.dimension.spawnEntity("minecraft:xp_orb", e.location)
    }
  }
  let id = getId(e);
  id.includes("_elemental")
  ? e.playAnimation(`animation.ld_eb_${id.replace("_elemental", "")}_mob.death`)
  : e.playAnimation(`animation.ld_eb_${id}.death`);
  id === "steel_behemoth" ? id = "steel_behemont" : null
  //console1-console.warn(id)
  mc.world.playSound(`ld_eb.${id}.hurt`, e.location, { pitch: random(17, 20) / 10, volume: 20 });
  mc.world.playSound(`ld_eb.${id}.hurt`, e.location, { pitch: random(4, 6) / 10, volume: 20 });
  e.addTag("ld_eb:dying");

  await mc.system.waitTicks((deathDelays[id] ?? 1) * 20);

  e.remove()
});

mc.world.afterEvents.entityLoad.subscribe(data => {
  if (data.entity.hasTag("ld_eb:dying")) data.entity.remove();
});

const getId = e => e.typeId.split(":").pop().replace(/^ld_eb_/, "");
