import { world, system, BlockPermutation, GameMode } from "@minecraft/server";

world.beforeEvents.itemUseOn.subscribe(eventData => {
  const player = eventData.source;
  const itemUsed = eventData.itemStack;
  const block = eventData.block;
  const blockLocation = block.location;
  const playerEquippable = player.getComponent("equippable");
  const statePillarAxis = block.permutation.getState("pillar_axis");
  const stateAll = block.permutation.getAllStates();
  const strippedWoods = [
    "nicothekid:mosshroom_hyphae_stripped",
    "nicothekid:mosshroom_stem_stripped"
  ]
  function decreaseItem () {
    if (!player.matches({ gameMode: GameMode.creative })) {
      const decrementItem = itemUsed.amount == 1 ? undefined : (itemUsed.amount--, itemUsed);
      playerEquippable.setEquipment("Mainhand", decrementItem)
    }
  }
  if (itemUsed === undefined) return;
  if (strippedWoods.includes(block.typeId)) {
    if (itemUsed.typeId === "minecraft:bone_meal") {
      system.run(() => {
        decreaseItem ();
        block.dimension.playSound("item.bone_meal.use", blockLocation, { pitch: 1.0, volume: 1.0 });
        block.dimension.spawnParticle("nicothekid:barked_2_particle", { x: blockLocation.x, y: blockLocation.y, z: blockLocation.z });
        if (block.permutation.matches("nicothekid:mosshroom_hyphae_stripped")) {
          block.setPermutation(BlockPermutation.resolve("nicothekid:mosshroom_hyphae", stateAll ));
          return;
        }
        if (block.permutation.matches("nicothekid:mosshroom_stem_stripped")) {
          block.setPermutation(BlockPermutation.resolve("nicothekid:mosshroom_stem", stateAll ));
          return;
        }
      });
    }
    else return;
  }
  else return;
});
