import { EntityEquippableComponent, EquipmentSlot, ItemDurabilityComponent, EntityInventoryComponent } from "@minecraft/server";

export default {
  isPotion(entity) {
    return entity.typeId == "minecraft:splash_potion";
  },
  damageWeapon(item, damage) {
    const durability = item?.getComponent(ItemDurabilityComponent.componentId);

    if (!durability) return item;
    durability.damage += damage;
    return item;
  },
  getEquipmentComponent(entity) {
    return entity.getComponent(EntityEquippableComponent.componentId);
  },
  getWeapon(player, offhand = false) {
    return this.getEquipmentComponent(player)
      .getEquipment(offhand ? EquipmentSlot.Offhand : EquipmentSlot.Mainhand);
  },
  calculateReduction(damage, damager, isProyectile = false) {
    if (!this.isPotion(damager) && isProyectile) return damage;
    return damage - (damage * 0.4);
  },
  findWeapon(player) {
    return [false, true]
      .map(offhand => this.getWeapon(player, offhand))
      .filter(item => item && this.hasTag(item, "minecraft:is_twohanded"))[0];
  },
  hasTag(itemStack, tag, tagRegexp = null) {
    return itemStack
      .getTags()
      .find(itemTag => tagRegexp ? tagRegexp.test(itemTag) : itemTag == tag);
  },
  getItemsWithTag(player, tag, tagRegexp = null) {
    const playerInventoryComponentContainer = player.getComponent(EntityInventoryComponent.componentId).container;
    const items = [];

    for (let i = 0; i < playerInventoryComponentContainer.size; i++) {
        const item = playerInventoryComponentContainer.getItem(i);

        if (!item) continue;
        if (this.hasTag(item, tag, tagRegexp)) items.push({ slot: i, item });
    }
    return items;
}
}