import {
  world
} from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockComponentRegistry.registerCustomComponent('we:grow_flowering_cactus', {
    onPlayerInteract(e) {
      const block = e.block.center();
      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)
      e.dimension.playSound('item.bone_meal.use', block)
      e.dimension.runCommandAsync(`loot spawn ${e.block.x} ${e.block.above().center().y} ${e.block.z} loot \"blocks/bone_meal/flowering_cactus\"`)
      
    }
  });

initEvent.blockComponentRegistry.registerCustomComponent('we:bone_meal_generic', {
    onPlayerInteract(e) {
      const block = e.block.center();
      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);
            }
          }

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

        blockId = blockId.replace('_block', '');

e.dimension.spawnParticle('minecraft:crop_growth_emitter', block)
      e.dimension.playSound('item.bone_meal.use', block)
      e.dimension.runCommandAsync(`loot spawn ${block.x + 0.25} ${block.y} ${block.z + 0.25} loot \"blocks/bone_meal/${blockId}\"`)
      
    }
  });
});