import {
  world
} from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe(initEvent => {

initEvent.blockComponentRegistry.registerCustomComponent('we:tick_sapling', {
    onTick(e) {
      const block = e.block;

        if (block.above().isAir && block.above(2).isAir && block.above(3).isAir) {

        var func = block.typeId.replace('we:', '');

        func = func.replace('_sapling_block', '');

        e.dimension.runCommandAsync(`execute positioned ${block.x} ${block.y} ${block.z} run function sapling/${func}`)
      }
    }
  });
  initEvent.blockComponentRegistry.registerCustomComponent('we:bone_meal_sapling', {
    onPlayerInteract(e) {
      const block = e.block;
      const player = e.player;
      const equipment = player.getComponent('equippable');
      const selectedItem = equipment.getEquipment('Mainhand');
      if (!selectedItem) return;
      if (selectedItem.typeId !== 'minecraft:bone_meal') return;
      if (!e.player.matches({
          gameMode: 'creative'
        })) {
        if (selectedItem.amount > 1) {
          selectedItem.amount -= 1;
          equipment.setEquipment('Mainhand', selectedItem);
        } else {
          equipment.setEquipment('Mainhand', undefined);
        }
      }
      e.dimension.spawnParticle('minecraft:crop_growth_emitter', block.center())
      e.dimension.playSound('item.bone_meal.use', block)

      const rand = Math.floor(Math.random() * 3);
      if (rand > 0) return;

      if (block.above().isAir && block.above(2).isAir && block.above(3).isAir) {

        var func = block.typeId.replace('we:', '');

        func = func.replace('_sapling_block', '');

        e.dimension.runCommandAsync(`execute positioned ${block.x} ${block.y} ${block.z} run function sapling/${func}`)
      }

    }
  });
});