import { world, system, BlockPermutation, GameMode } from "@minecraft/server";

world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockTypeRegistry.registerCustomComponent("nicothekid:overgrown_jungle_plant_growth", {
    onPlayerInteract: eventData => {
      const player = eventData.player;
      const block = eventData.block;
      const blockLocation = block.location;
      const playerEquippable = player.getComponent("equippable");
      const itemUsed = playerEquippable.getEquipment("Mainhand");
      function decreaseItem () {
        if (!player.matches({ gameMode: GameMode.creative })) {
          const decrementItem = itemUsed.amount == 1 ? undefined : (itemUsed.amount--, itemUsed);
          playerEquippable.setEquipment("Mainhand", decrementItem)
        }
      }
      if (itemUsed === undefined) return;
      if (block.typeId === "nicothekid:overgrown_jungle_plant" && itemUsed.typeId === "minecraft:bone_meal") {
        system.run(() => {
          let randomChance = Math.random() * (100.0 - 0.0) + 0.0;
          decreaseItem ();
          block.dimension.playSound("item.bone_meal.use", blockLocation, { pitch: 1.0, volume: 1.0 });
          block.dimension.spawnParticle("minecraft:crop_growth_emitter", { x: blockLocation.x + 0.5, y: blockLocation.y + 0.5, z: blockLocation.z + 0.5 });
          if (randomChance <= 40.0) {
            let randomVariation = Math.random() * (100.0 - 0.0) + 0.0;
            if (randomVariation <= 50.0) {
              block.setPermutation(BlockPermutation.resolve("minecraft:air"));
              block.dimension.runCommandAsync(`structure load overgrown_jungle_tree_01 ${blockLocation.x - 7} ${blockLocation.y - 2} ${blockLocation.z - 7}`);
            }
            else if (randomVariation <= 100.0) {
              block.setPermutation(BlockPermutation.resolve("minecraft:air"));
              block.dimension.runCommandAsync(`structure load overgrown_jungle_tree_02 ${blockLocation.x - 5} ${blockLocation.y - 1} ${blockLocation.z - 5}`);
            }
            else return;
          }
          else return;
        });
      }
      else return;
    }
  });
})
