import * as mc from "@minecraft/server";
import * as vector from "./utils/vector";
import * as earthrend from "./items/earthrendGauntlet";

export function carveCave(event) {
  if (event.id === "hf_mzs:carve_cave") {
    const entity = event.sourceEntity;
    if (entity && entity.isValid() && !entity.hasTag("hf_mzs_cave_carver_triggered")) {
      entity.addTag("hf_mzs_cave_carver_triggered");
      const radius = Math.floor(Math.random() * 2 + 3);
      const iterations = Math.floor(Math.random() * 10) + 20;
      caveCarver(entity, radius, iterations, 1);
    }
  }
}

function caveCarver(entity, radius, maxIterations, iteration) {
  if (iteration > maxIterations / 3 && (iteration > maxIterations || !earthrend.isUnderground(entity, radius + 2))) {
    // mc.world.sendMessage(`Cave carving finished ${entity.location.x} ${entity.location.y} ${entity.location.z}`);
    entity.remove();
    return;
  }

  const center = entity.location;
  const dir = entity.getViewDirection();

  for (let i = -radius; i <= radius; i++) {
    for (let j = -radius; j <= radius; j++) {
      for (let k = -radius; k <= radius; k++) {
        if (center.y + k <= entity.dimension.heightRange.min || center.y + k > entity.dimension.heightRange.max) continue;
        let block = entity.dimension.getBlock({ x: center.x + i, y: center.y + k, z: center.z + j });

        let dist = vector.distance(center, block);

        if (block && block.isValid() && block.typeId !== "minecraft:bedrock" && dist < radius) {
          block.setPermutation(mc.BlockPermutation.resolve("minecraft:air"));
        }
      }
    }
  }

  if (iteration > maxIterations / 3) {
    dir.x += (Math.round(Math.random() * 2) - 1) * Math.random() * 3;
    dir.z += (Math.round(Math.random() * 2) - 1) * Math.random() * 3;
  }
  dir.y = Math.random() / 2;
  entity.clearVelocity();
  entity.applyImpulse(dir);
  mc.system.runTimeout(() => {
    caveCarver(entity, radius, maxIterations, iteration + 1);
  }, 1);
}
