import { world, BlockPermutation, system } from "@minecraft/server";
import { castSpellProjectile } from "./Spells";
import { Vector3 } from "../Vector3";
import { spawnParticle } from "../SpawnParticle";

//Function run when using the spell
export function spongeSpell(player) {
  player.sendMessage(`<${player.nameTag}> Drying spell!`);
  castSpellProjectile(player, "blockception_magic:sponge_spell", 2);
}

//Checking if blocks are water
function blockIsWater(block) {
  if (block.typeId == "minecraft:water" || block.typeId == "minecraft:flowing_water") {
    return true;
  } else {
    return false;
  }
}

function blockKey(x, y, z) {
  return `${x},${y},${z}`
}

const directions = [
  {x: 0, y: 1, z: 0},
  {x: 0, y: -1, z: 0},
  {x: 1, y: 0, z: 0},
  {x: -1, y: 0, z: 0},
  {x: 0, y: 0, z: 1},
  {x: 0, y: 0, z: -1},
]

export function spongeSpellEvent(location, dimension) {
  const checkedBlocks = new Set();
  const queue = [location];
  const maxBlocks = 64;

  let count = 0

  while (queue.length > 0 && count < maxBlocks) {
    const {x, y, z} = queue.shift();
    const key = blockKey(x, y, z);
    if (checkedBlocks.has(key)) {
      continue;
    };

    checkedBlocks.add(key);

    const block = world.getDimension(dimension.id).getBlock(new Vector3(x, y, z));
    if (blockIsWater(block)) {
      spawnParticle("blockception_magic:sponge_spell_fog", block.location, block.dimension);
      block.setPermutation(BlockPermutation.resolve("minecraft:air"));
      count++;
    }

    for (const dir of directions) {
      const neighbour = new Vector3(x + dir.x, y + dir.y, z + dir.z);
      const neighbourKey = blockKey(neighbour);
      const neighbourBlock = world.getDimension(dimension.id).getBlock(neighbour);
      if (blockIsWater(neighbourBlock) && !checkedBlocks.has(neighbourKey)) {
        queue.push(neighbour);
      }
    }
  }
}