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

export default function juiceFruit(juicer, fruit, player) {
  const dimension = player.dimension;
  let juicerPermutation, newPermutation, Fruit, newFruitInt, currentFruitState, fillstage, direction;
  juicerPermutation = juicer.permutation;
  Fruit = fruit.typeId;
  if (Fruit == "float_fc:chopped_pear_fruit") {
    newFruitInt = 1;
  } else if (Fruit == "float_fc:chopped_lemon_fruit") {
    newFruitInt = 2;
  } else if (Fruit == "float_fc:chopped_peach_fruit") {
    newFruitInt = 3;
  } else if (Fruit == "float_fc:chopped_orange_fruit") {
    newFruitInt = 4;
  } else if (Fruit == "float_fc:chopped_cherry_fruit") {
    newFruitInt = 5;
  } else if (Fruit == "float_fc:chopped_banana_fruit") {
    newFruitInt = 6;
  } else if (Fruit == "float_fc:chopped_mango_fruit") {
    newFruitInt = 7;
  } else if (Fruit == "float_fc:chopped_frozen_berry_fruit") {
    newFruitInt = 8;
  } else if (Fruit == "float_fc:chopped_coconut_fruit") {
    newFruitInt = 9;
  } else if (Fruit == "float_fc:chopped_plum_fruit") {
    newFruitInt = 10;
  } else if (Fruit == "float_fc:chopped_rainbow_fruit") {
    newFruitInt = 11;
  } else if (Fruit == "float_fc:chopped_walnut_fruit") {
    newFruitInt = 12;
  } else if (Fruit == "float_fc:chopped_apple_fruit") {
    newFruitInt = 13;
  } else if (Fruit == "float_fc:chopped_hazelnut_fruit") {
    newFruitInt = 14;
  } else if (Fruit == "float_fc:chopped_cactus_fruit") {
    newFruitInt = 15;
  }

  // Get the current fruit state from the juicer
  currentFruitState = juicerPermutation.getState("float_fc:fruit");

  // Check if the current fruit state is 0 or matches the new fruit being added
  if (currentFruitState == 0 || currentFruitState == newFruitInt) {
    if (player.hasTag("juicer_tutorial")) {
      player.runCommand(`event entity @e[type=float_fc:chopped_fruit_want_particle,r=8] float_fc:kill_entity`);
      player.removeTag("juicer_tutorial");
    }
    fillstage = juicerPermutation.getState("float_fc:fill_stage");
    direction = juicerPermutation.getState("minecraft:cardinal_direction");
    fillstage++;
    player.playSound("float_fc.juice_fruit");

    newPermutation = BlockPermutation.resolve("float_fc:juicer", {
      "float_fc:fruit": newFruitInt,
      "float_fc:fill_stage": fillstage,
      "minecraft:cardinal_direction": direction,
    });
    if (fillstage == 2 && player.hasTag("juicer_tutorial_glass")) {
      dimension.runCommand(
        `summon float_fc:glass_want_particle ${juicer.center().x} ${juicer.center().y + 0.5} ${juicer.center().z}`
      );
    }
    if (newPermutation) {
      juicer.setPermutation(newPermutation);
      player.runCommand(`clear @s ${Fruit} -1 1`);
    }
  }
  juicerPermutation = newPermutation = Fruit = newFruitInt = currentFruitState = fillstage = direction = undefined;
}
