import { EntityHealthComponent, Player } from "@minecraft/server";

const identifier = "myth:life_essence";

/** @param {Player} player */
function getAmplifier(player) {
  const level = player.getDynamicProperty(identifier);
  if (typeof level !== "number") {
    return 0;
  }
  return level;
}

/** @param {Player} player */
export function lifeEssenceTick(player) {
  const amplifier = getAmplifier(player);
  if (!amplifier) {
    return;
  }
  player.addEffect("health_boost", 2e7, {
    amplifier: amplifier - 1,
    showParticles: false,
  });
}

/** @param {Player} player */
export function lifeEssenceUse(player) {
  const amplifier = getAmplifier(player);
  if (amplifier >= 5) {
    player.sendMessage("You have acquired the maximum amount of hearts!");
    return;
  }

  const health = player.getComponent(EntityHealthComponent.componentId);
  if (health instanceof EntityHealthComponent && health.effectiveMax >= 40) {
    player.triggerEvent("myth:reset_max_health");
    player.setDynamicProperty(identifier, amplifier + 1);
    player.sendMessage("You have acquired the maximum amount of hearts!");
  } else {
    player.setDynamicProperty(identifier, amplifier + 1);
    player.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 0 air`);
    player.playSound("civ.myth.item.consume");
  }
}
