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

world.beforeEvents.worldInitialize.subscribe(initEvent => {
  const mossSprouts = [
    "nicothekid:moss_sprouts_small_block"
  ]
  const boneMeals = [
    "minecraft:bone_meal"
  ]
  initEvent.blockTypeRegistry.registerCustomComponent("nicothekid:moss_sprouts_growth", {
    onPlayerInteract: eventData => {
      const player = eventData.player;
      const block = eventData.block;
      const blockLocation = block.location;
      const playerEquippable = player.getComponent("equippable");
      const itemUsed = playerEquippable.getEquipment("Mainhand");
      function decreaseItem () {
        system.run(() => {
          if (!player.matches({ gameMode: GameMode.creative })) {
            const decrementItem = itemUsed.amount == 1 ? undefined : (itemUsed.amount--, itemUsed);
            playerEquippable.setEquipment("Mainhand", decrementItem)
          }
        });
      }
      if (itemUsed === undefined) return;
      if (mossSprouts.includes(block.typeId) && boneMeals.includes(itemUsed.typeId)) {
        if (block.typeId === "nicothekid:moss_sprouts_small_block" && itemUsed.typeId === "minecraft:bone_meal") {
          decreaseItem ();
          block.dimension.playSound("item.bone_meal.use", blockLocation, { pitch: 1.0, volume: 1.0 });
          block.dimension.spawnParticle("minecraft:crop_growth_emitter", { x: blockLocation.x + 0.5, y: blockLocation.y + 0.5, z: blockLocation.z + 0.5 });
          block.setPermutation(BlockPermutation.resolve("nicothekid:moss_sprouts_tall_block"));
          return;
        }
        else return;
      }
      else return;
    }
  });
})
