import { getRandomNumber } from "./helpers.js";

export function decreaseDurability(player) {
  const equippable = player.getComponent("minecraft:equippable");
  const mainHand = equippable.getEquipment("Mainhand");
  if (!mainHand) return;

  const durabilityComponent = mainHand.getComponent('minecraft:durability');
  if (!durabilityComponent) return;

  const enchantable = mainHand.getComponent('minecraft:enchantable');

  if (enchantable) {
    for (const enchant of enchantable.getEnchantments()) {
      if (enchant.type.id != "unbreaking") continue;
      let chance = getRandomNumber(1, 100);
      const unbreakingChances = [0, 50, 66, 75];

      if (chance <= unbreakingChances[enchant.level])
        return

    }
  }

  durabilityComponent.damage += 1;
  durabilityComponent.damage = Math.min(durabilityComponent.damage, durabilityComponent.maxDurability);

  if (durabilityComponent.damage >= durabilityComponent.maxDurability) {
    player.runCommand("/playsound random.break @s");
    player.runCommand("/replaceitem entity @s slot.weapon.mainhand 0 minecraft:air");
    return;
  }

  equippable.setEquipment("Mainhand", mainHand);
}

export function decreaseDurabilityAmount(player, amount) {
  const equippable = player.getComponent("minecraft:equippable");
  const mainHand = equippable.getEquipment("Mainhand");
  if (!mainHand) return;

  const durabilityComponent = mainHand.getComponent('minecraft:durability');
  if (!durabilityComponent) return;

  const enchantable = mainHand.getComponent('minecraft:enchantable');

  if (enchantable) {
    for (const enchant of enchantable.getEnchantments()) {
      if (enchant.type.id != "unbreaking") continue;

      for (let i = 0; i < amount; i++) {
        let chance = getRandomNumber(1, 100);
        const unbreakingChances = [0, 50, 66, 75];

        if (chance <= unbreakingChances[enchant.level])
          amount -= 1
      }

    }
  }

  durabilityComponent.damage += amount;
  durabilityComponent.damage = Math.min(durabilityComponent.damage, durabilityComponent.maxDurability);
  
  if (durabilityComponent.damage >= durabilityComponent.maxDurability) {
    player.runCommand("/playsound random.break @s");
    player.runCommand("/replaceitem entity @s slot.weapon.mainhand 0 minecraft:air");
    return;
  }

  equippable.setEquipment("Mainhand", mainHand);
}