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

export default function growTree_nonplayer(location, sapling, fruit, dimension) {
  const overworld = world.getDimension("overworld");
  const rotations = ["0_degrees", "180_degrees", "270_degrees", "90_degrees"];
  const randomIndex = Math.floor(Math.random() * rotations.length);
  const treernd = Math.floor(Math.random() * 4);
  const rnd_rot = rotations[randomIndex];
  const offsetX1 = location.x - 2;
  const offsetY1 = location.y;
  const offsetZ1 = location.z - 2;
  const offsetX2 = location.x - 2;
  const offsetY2 = location.y;
  const offsetZ2 = location.z - 2;
  const offsetX3 = location.x - 3;
  const offsetY3 = location.y;
  const offsetZ3 = location.z - 3;
  const offsetX4 = location.x - 4;
  const offsetY4 = location.y;
  const offsetZ4 = location.z - 4;

  const fruitParts = fruit.split(":");
  const fruitName = fruitParts.length > 1 ? fruitParts[1].split("_")[0] : fruitParts[0];
  const structureName = `${fruitName}_tree`;

  if (treernd === 0) {
    dimension.runCommand(
      `structure load "float_fc/${structureName}_5x5_1" ${offsetX1} ${offsetY1} ${offsetZ1} ${rnd_rot} none layer_by_layer 3`
    );
    system.runTimeout(() => {
      dimension.runCommand(
        `event entity @e[type=${fruit},x=${offsetX1},y=${offsetY1},z=${offsetZ1},r=10] float_fc:start_growing`
      );
    }, 100);
  }
  if (treernd === 1) {
    dimension.runCommand(
      `structure load "float_fc/${structureName}_5x5_2" ${offsetX2} ${offsetY2} ${offsetZ2} ${rnd_rot} none layer_by_layer 3`
    );
    system.runTimeout(() => {
      dimension.runCommand(
        `event entity @e[type=${fruit},x=${offsetX2},y=${offsetY2},z=${offsetZ2},r=10] float_fc:start_growing`
      );
    }, 100);
  }
  if (treernd === 2) {
    dimension.runCommand(
      `structure load "float_fc/${structureName}_7x7_3" ${offsetX3} ${offsetY3} ${offsetZ3} ${rnd_rot} none layer_by_layer 3`
    );
    system.runTimeout(() => {
      dimension.runCommand(
        `event entity @e[type=${fruit},x=${offsetX3},y=${offsetY3},z=${offsetZ3},r=10] float_fc:start_growing`
      );
    }, 100);
  }
  if (treernd === 3) {
    dimension.runCommand(
      `structure load "float_fc/${structureName}_9x9_4" ${offsetX4} ${offsetY4} ${offsetZ4} ${rnd_rot} none layer_by_layer 3`
    );
    system.runTimeout(() => {
      dimension.runCommand(
        `event entity @e[type=${fruit},x=${offsetX4},y=${offsetY4},z=${offsetZ4},r=10] float_fc:start_growing`
      );
    }, 100);
  }
}
