import { system, world } from '@minecraft/server';

function durabilityOnChanged(item, player, isHitEntity = false) {
  let level = item.getComponent("minecraft:enchantable")?.getEnchantment("unbreaking")?.level;

  function durability() {
    let durability = item.getComponent("minecraft:durability");
    const t = Math.floor(Math.random() * 100);

    if (t < durability.getDamageChance()) {
      if (!isHitEntity) durability.damage += 1;
      if (durability.damage >= durability.maxDurability) {
        player.playSound("random.break");
        if (!isHitEntity) player.getComponent('equippable').setEquipment('Mainhand', undefined);
      } else {
        if (!isHitEntity) player.getComponent('equippable').setEquipment('Mainhand', item);
      }
    } else {
      if (!isHitEntity) return;
      durability.damage -= 1;
      if (!isHitEntity) player.getComponent('equippable').setEquipment('Mainhand', item);
    }
  }

  const t = Math.floor(Math.random() * 10);
  if (level === 1 && t > 8) return;
  else if (level === 2 && t > 6) return;
  else if (level === 3 && t > 4) return;
  else durability();
}

world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.itemComponentRegistry.registerCustomComponent('besmc_close_door:trigger', {
    onUse: e => { e.source.runCommandAsync("event entity @e[family=door_open, c=1, r=10] close"); },
  });
});

world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.itemComponentRegistry.registerCustomComponent('besmc_open_door:trigger', {
    onUse: e => { e.source.runCommandAsync("event entity @e[family=door_close, c=1, r=10] open"); },
  });
});

const grabpacks = [
  { change: 'mebesm:change_grabpack_gb', items: ['mebesm:grabpack_blue_g', 'mebesm:grabpack_green', 'mebesm:grabpack_green_and_blue'], tag: 'gp_gb' },
  { change: 'mebesm:change_grabpack_ob', items: ['mebesm:grabpack_blue_o', 'mebesm:grabpack_orange'], tag: 'gp_ob' },
  { change: 'mebesm:change_grabpack_omb', items: ['mebesm:grabpack_blue_om', 'mebesm:grabpack_omni', 'mebesm:grabpack_omni_and_blue'], tag: 'gp_omb' },
  { change: 'mebesm:change_grabpack_prb', items: ['mebesm:grabpack_blue_pr', 'mebesm:grabpack_pressure', 'mebesm:grabpack_pressure_and_blue'], tag: 'gp_prb' },
  { change: 'mebesm:change_grabpack_pb', items: ['mebesm:grabpack_blue_p', 'mebesm:grabpack_purple', 'mebesm:grabpack_purple_and_blue'], tag: 'gp_pb' },
  { change: 'mebesm:change_grabpack_rb', items: ['mebesm:grabpack_blue_r', 'mebesm:grabpack_red', 'mebesm:grabpack_red_and_blue'], tag: 'gp_rb' },
  { change: 'mebesm:change_grabpack_yb', items: ['mebesm:grabpack_blue_y', 'mebesm:grabpack_yellow', 'mebesm:grabpack_yellow_and_blue'], tag: 'gp_yb' }
];

world.afterEvents.itemUse.subscribe(ev => {
  const player = ev.source;
  const itemId = ev.itemStack.typeId;

  const pack = grabpacks.find(p => p.change === itemId);
  if (pack) {
    system.run(() => {
      player.runCommandAsync(`clear @s ${pack.change} 0 1`);
      pack.items.forEach(item => {
        player.runCommandAsync(`give @s ${item} 1 0 {"item_lock": {"mode": "lock_in_inventory"}}`);
      });
      player.runCommandAsync(`give @s mebesm:clear_grabpack 1 0 {"item_lock": {"mode": "lock_in_inventory"}}`);
      player.addTag(pack.tag);
    });
    return;
  }

  if (itemId === 'mebesm:clear_grabpack') {
    system.run(() => {
      for (const pack of grabpacks) {
        if (player.hasTag(pack.tag)) {
          pack.items.forEach(item => {
            player.runCommandAsync(`clear @s ${item} 0 1`);
          });
          player.runCommandAsync(`clear @s mebesm:clear_grabpack 0 1`);
          player.runCommandAsync(`give @s ${pack.change}`);
          player.removeTag(pack.tag);
          break;
        }
      }
    });
  }
});