import { world, SoundOptions, Location } from "mojang-minecraft";

world.events.beforeItemUseOn.subscribe(data => {
  const { blockLocation, source } = data;
  const block = source.dimension.getBlock(blockLocation);

  if (!source.hasTag("morph:stored_nectar") && (source.getComponent("minecraft:variant").value == 40 && source.getComponent("minecraft:is_charged")) && (block.id == "minecraft:bee_nest" || block.id == "minecraft:beehive")) {
    source.addTag("morph:stored_nectar");
    source.triggerEvent("morph:bee_collect_nectar");

    let store_nectar = block.permutation;
    store_nectar.getProperty("honey_level").value = store_nectar.getProperty("honey_level").value < 5 ? store_nectar.getProperty("honey_level").value + 1 : store_nectar.getProperty("honey_level").value + 0;
    block.setPermutation(store_nectar);

    let store_sound = new SoundOptions();
    store_sound.location = new Location(block.location.x, block.location.y, block.location.z);
    world.playSound("block.beehive.enter", store_sound);

    let end = () => {
      if (!source.getComponent("minecraft:is_charged")) {
        source.removeTag("morph:stored_nectar");
        world.events.tick.unsubscribe(end);
      };
    };
    world.events.tick.subscribe(end);
  };
});