import { world } from "@minecraft/server";
import { forestryLogsandWood, forestryLeaves } from "../globals";

export default function fruitshaker(player, blockOrPermutation, location, blockid) {
  let blockPermutation, fruit, entities, loot;
  let dimension = player.dimension;

  // Ensure the block is part of the tree (log or leaf)
  blockPermutation = blockOrPermutation.permutation ? blockOrPermutation.permutation : blockOrPermutation;
  if (
    Array.from(forestryLeaves).find((leaves) => blockPermutation.matches(leaves)) ||
    Array.from(forestryLogsandWood).find((log) => blockPermutation.matches(log))
  ) {
    // Perform the fruit harvesting in one go
    if (blockid.includes("log") || blockid.includes("wood")) {
      fruit = blockid.replace("log", "leaf").replace("wood", "leaf");
    } else {
      fruit = blockid; // Default fallback if not a log or wood
    }

    if (fruit === "float_fc:snow_crystal_leaf") {
      fruit = "float_fc:frozen_berry_leaf";
    }
    if (fruit === "minecraft:oak_leaf") {
      fruit = "float_fc:apple_leaf";
    }

    player.playSound("float_fc.tree_shaker");
    dimension.runCommand(`particle ${fruit} ${location.x} ${location.y + 5} ${location.z}`);
    dimension.runCommand(`particle ${fruit} ${location.x} ${location.y + 5} ${location.z}`);
    dimension.runCommand(`particle ${fruit} ${location.x} ${location.y + 6} ${location.z}`);

    // Retrieve entities of the current type within a 10-block radius horizontally and a 30-block radius vertically
    entities = player.dimension.getEntities({
      type: fruit,
      location: location,
      maxDistance: 20,
      maxVerticalDistance: 40,
    });

    // Process each entity found
    entities.forEach((entity) => {
      if (entity.getProperty("float_fc:growth_stage") === 5) {
        entity.triggerEvent("float_fc:harvest_fruit");
        loot = fruit.replace("float_fc:", "");
        dimension.runCommand(
          `loot spawn ${entity.location.x} ${entity.location.y} ${entity.location.z} loot "float/f/${loot}"`
        );
      }
    });

    entities = fruit = loot = undefined;
  }
  blockPermutation = undefined;
}
