import {
  world,
  BlockPermutation,
  ItemStack,
  system
} from "@minecraft/server";
world.beforeEvents.itemUseOn.subscribe((event) => {

  const player = event.source;
  const block = event.block

  const equipment = player.getComponent('equippable');
  const selectedItem = equipment.getEquipment('Mainhand');

  if (!selectedItem?.hasTag('minecraft:is_axe')) return;


  //Baobab tree has a special block that looks like wood but has properties of log
  if (block.hasTag('we:strippable_world_gen_top')) {
system.run(() => {
      if (!player.matches({
          gameMode: 'creative'
        })) {

         const durability = selectedItem.getComponent('durability');

        if (durability && durability.damage < durability.maxDurability) {
          durability.damage++;
          equipment.setEquipment('Mainhand', selectedItem);
        }
        if (durability && durability.damage >= durability.maxDurability) {
          player.playSound('random.break');
          equipment.setEquipment('Mainhand', new ItemStack('minecraft:air', 1));
        }
      }
      const blockState = block.permutation.getState("minecraft:block_face");

      var blockId = block.typeId.replace('we:', 'we:stripped_');
      blockId = blockId.replace('world_gen_top', 'log');

      if (blockState) {
        const strippedLog = BlockPermutation.resolve(blockId, {
          "minecraft:block_face": blockState
        });

        block.setPermutation(strippedLog);
      }
      player.playSound('step.cherry_wood');
    })
    return;
  }


  if (block.hasTag('we:strippable_log')) {
    system.run(() => {
      if (!player.matches({
          gameMode: 'creative'
        })) {

         const durability = selectedItem.getComponent('durability');

        if (durability && durability.damage < durability.maxDurability) {
          durability.damage++;
          equipment.setEquipment('Mainhand', selectedItem);
        }
        if (durability && durability.damage >= durability.maxDurability) {
          player.playSound('random.break');
          equipment.setEquipment('Mainhand', new ItemStack('minecraft:air', 1));
        }
      }
      const blockState = block.permutation.getState("minecraft:block_face");

      const blockId = block.typeId.replace('we:', 'we:stripped_');

      if (blockState) {
        const strippedLog = BlockPermutation.resolve(blockId, {
          "minecraft:block_face": blockState
        });

        block.setPermutation(strippedLog);
      }
      player.playSound('step.cherry_wood');
    })
  }
})


// uses a beforeEvent rather than custom component to get around an annoying bug 