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

const ores = new Set([
  "minecraft:coal_ore",
  "minecraft:gold_ore",
  "minecraft:iron_ore",
  "minecraft:lapis_ore",
  "minecraft:copper_ore",
  "minecraft:diamond_ore",
  "minecraft:emerald_ore",
  "minecraft:redstone_ore",
  "minecraft:lit_redstone_ore",
  "minecraft:deepslate_coal_ore",
  "minecraft:deepslate_gold_ore",
  "minecraft:deepslate_iron_ore",
  "minecraft:deepslate_lapis_ore",
  "minecraft:deepslate_copper_ore",
  "minecraft:deepslate_diamond_ore",
  "minecraft:deepslate_emerald_ore",
  "minecraft:deepslate_redstone_ore",
  "minecraft:lit_deepslate_redstone_ore",
  "minecraft:quartz_ore",
  "minecraft:nether_gold_ore",
].map((ore) => BlockPermutation.resolve(ore)));

const oreItems = new Set([
  "minecraft:coal",
  "minecraft:raw_gold",
  "minecraft:raw_iron",
  "minecraft:lapis_lazuli",
  "minecraft:raw_copper",
  "minecraft:quartz",
  "minecraft:diamond",
  "minecraft:emerald",
  "minecraft:redstone",
  "minecraft:gold_nugget",
]);

/**
 * @param {import("@minecraft/server").Player} player
 */
export async function magneticWand(player) {
  const dimension = player.dimension;
  const location = {
    x: Math.floor(player.location.x),
    y: Math.floor(player.location.y),
    z: Math.floor(player.location.z),
  };

  for (let y = location.y - 7; y <= location.y + 7; y++) {
    const commands = [];
    for (let x = location.x - 7; x <= location.x + 7; x++) {
      for (let z = location.z - 7; z <= location.z + 7; z++) {
        const block = player.dimension.getBlock({ x, y, z });
        if (!block || !ores.has(block.permutation)) {
          continue;
        }
        commands.push(
          player.runCommandAsync(`setblock ${x} ${y} ${z} air destroy`),
        );
      }
    }
    await Promise.all(commands);
  }
  for (const entity of dimension.getEntities({ location, maxDistance: 15 })) {
    const item = entity.getComponent(EntityItemComponent.componentId);
    if (item instanceof EntityItemComponent && oreItems.has(item.itemStack.typeId)) {
      entity.teleport(location);
    }
  }
}
