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

world.beforeEvents.worldInitialize.subscribe(initEvent => {
  const lushGrasses = [
    "nicothekid:lush_grass_small_block"
  ]
  const boneMeals = [
    "minecraft:bone_meal"
  ]
  initEvent.blockTypeRegistry.registerCustomComponent("nicothekid:lush_grass_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 (lushGrasses.includes(block.typeId) && boneMeals.includes(itemUsed.typeId)) {
        if (block.typeId === "nicothekid:lush_grass_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:lush_grass_tall_block"));
          return;
        }
        else return;
      }
      else return;
    }
  });
})
