import * as mc from "@minecraft/server";

export function onUse(event) {
  mc.system.run(() => {
    const item = event.itemStack;
    const player = event.source;
    const block = event.block;

    if (item.typeId === "hf_mzs:foliaath_seed" && event.isFirstEvent) {
      if (block.typeId === "minecraft:grass_block" || block.typeId === "minecraft:dirt") {
        const bl = block.above();
        if (bl && bl.isValid()) {
          const entities = bl.dimension.getEntitiesAtBlockLocation(bl.location);
          let foliaaths = 0;

          for (const entity of entities)
            if (entity.typeId === "hf_mzs:foliaath" || entity.typeId === "hf_mzs:foliaath_baby") foliaaths++;

          if (foliaaths === 0) {
            player.runCommand("/clear @s hf_mzs:foliaath_seed 0 1");
            const loc = bl.location;
            loc.x = Math.floor(loc.x) + 0.5;
            loc.z = Math.floor(loc.z) + 0.5;
            bl.dimension.spawnEntity("hf_mzs:foliaath_baby", loc);
          }
        }
      }
    }
  });
}
