import {
  world,
  ItemStack,
  system
} from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockComponentRegistry.registerCustomComponent('we:grow_blueberry', {
    onRandomTick(e) {
      const {
        block
      } = e;

      if (block.typeId === 'minecraft:air') return;

      const random = Math.floor(Math.random() * 9);
      if (random !== 0) return;

      const permutation = block.permutation;

        const newPermutation = permutation.withState('we:growth', permutation.getState('we:growth')+1);
        block.setPermutation(newPermutation);
      
    },
    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);
            }
          }

        const permutation = e.block.permutation;
        const newPermutation = permutation.withState('we:growth', permutation.getState('we:growth')+1);
        e.block.setPermutation(newPermutation);

e.dimension.spawnParticle('minecraft:crop_growth_emitter', block)
      e.dimension.playSound('item.bone_meal.use', block)
    }
  });

initEvent.blockComponentRegistry.registerCustomComponent('we:harvest_blueberry', {
    onPlayerInteract(e) {
      const block = e.block.center();
      const player = e.player;

      const berryCount = Math.floor(Math.random()*3) + 1;
      

      const permutation = e.block.permutation;
      const newPermutation = permutation.withState('we:growth', 1);
      e.block.setPermutation(newPermutation);

      const berries = new ItemStack('we:blueberries', berryCount);
        system.runTimeout(() => {
          e.dimension.spawnItem(berries, block);
        }, 1);
        e.dimension.playSound('block.sweet_berry_bush.pick', block)
    }
  });
});