import { world, system } from "@minecraft/server";
export default function growTreeFruit(location, fruit, playerplaced, dimension) {
  let treernd,
    leaf,
    structureName,
    rnd_rot,
    randomIndex,
    offsetX,
    offsetY,
    offsetZ,
    randStruct,
    fruitParts,
    fruitName,
    result;
  try {
    if (location != undefined) {
      const overworld = world.getDimension("overworld");
      const rotations = ["0_degrees", "180_degrees", "270_degrees", "90_degrees"];
      dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} air replace`);
      randomIndex = Math.floor(Math.random() * 4.0);
      rnd_rot = rotations[randomIndex];
      if (playerplaced) {
        treernd = Math.floor(Math.random() * 4.0);
      } else {
        treernd = Math.floor(Math.random() * 4.0);
      }
      if (treernd > 2.0) {
        randStruct = "9x9_4";
        offsetX = location.x - 4;
        offsetZ = location.z - 4;
      } else if (treernd > 1.0) {
        randStruct = "7x7_3";
        offsetX = location.x - 3;
        offsetZ = location.z - 3;
      } else {
        randStruct = "5x5_1";
        offsetX = location.x - 2;
        offsetZ = location.z - 2;
      }
      offsetY = Math.round(location.y);
      leaf = fruit.replace("sapling", "leaf");
      fruitParts = fruit.split(":");
      fruitName = fruitParts.length > 1 ? fruitParts[1].split("_")[0] : fruitParts[0];
      structureName = `${fruitName}_tree`;
      if (structureName == "snow_tree") {
        structureName = "snow_crystal_tree";
        leaf = "float_fc:frozen_berry_leaf";
      }
      dimension.runCommand(
        `structure load "float_fc/${structureName}_${randStruct}" ${offsetX} ${offsetY} ${offsetZ} ${rnd_rot} none layer_by_layer 3`
      );
      result = `event entity @e[type=${leaf},x=${offsetX},y=${offsetY},z=${offsetZ},r=20] float_fc:fully_grown`;
      treernd =
        leaf =
        structureName =
        rnd_rot =
        randomIndex =
        offsetX =
        offsetY =
        offsetZ =
        randStruct =
        fruitParts =
        fruitName =
          undefined;
      return result;
    }
  } catch (e) {}
}
