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

export default function shearLeaf(leaf, item, leafID) {
  const leafPerm = leaf.permutation;
  const dimension = world.getDimension("overworld");
  const invalidStates = ["old_leaf_type", "persistent_bit", "update_bit"];
  let newPermutation, leaftoair, leafraw, states, key, value;
  leaftoair = "minecraft:air";
  if (
    leafID.startsWith("minecraft:") &&
    (item == "float_fc:shear_axe" || item == "minecraft:shears") &&
    leafID != "minecraft:cherry_leaves"
  ) {
    let leafraw = leafID.slice(10);
    dimension.runCommand(`loot spawn ${leaf.x} ${leaf.y} ${leaf.z} loot "float/f/shear/${leafraw}"`);
  } else if (leafID != "minecraft:cherry_leaves") {
    let leafraw = leafID.slice(9);
    dimension.runCommand(`loot spawn ${leaf.x} ${leaf.y} ${leaf.z} loot "float/f/shear/${leafraw}"`);
  }
  if (leafID.startsWith("minecraft:")) {
    newPermutation = BlockPermutation.resolve(leaftoair);
    states = leafPerm.getAllStates();
    if (leafID == "minecraft:cherry_leaves") {
      dimension.runCommand(`loot spawn ${leaf.x} ${leaf.y} ${leaf.z} loot "float/f/shear/vanilla_cherry"`);
    }
    for ([key, value] of Object.entries(states)) {
      if (!invalidStates.includes(key)) {
        newPermutation = newPermutation.withState(key, value);
      }
    }
  } else {
    newPermutation = BlockPermutation.resolve(leaftoair);
  }
  if (newPermutation) {
    leaf.setPermutation(newPermutation);
  }
  newPermutation = leaftoair = leafraw = states = key = value = undefined;
}
