import { world } from "@minecraft/server";
import { Vector3 } from "../Vector3";

//Set of entities the function has already run on
const processedEntities = new Set();

//Function run when using the spell
export function pushSpell(player) {
  player.sendMessage(`<${player.nameTag}> Force spell!`);
  //Particles
  const dimension = player.dimension;
  const yaw = player.getRotation().y;
  const radYaw = yaw * (Math.PI / 180);
  const spawnLoc = new Vector3(player.location.x - Math.sin(radYaw), player.location.y + 0.25, player.location.z + Math.cos(radYaw));
  let particleEntity = dimension.spawnEntity("blockception_magic:push_spell", spawnLoc);
  particleEntity.setProperty("spell:rotation", Math.round(yaw));

  //Spell Function
  processedEntities.clear();
  const halfAngle = 30;
  const reach = 9;
  const startRotation = (player.getRotation().y) - halfAngle;
  const endRotation = (player.getRotation().y) + halfAngle;

  for (let angle = startRotation + 90; angle <= endRotation + 90; angle += 5) {
    for (let distance = 2; distance <= reach; distance++) {
      const radAngle = angle * (Math.PI / 180);
      const offsetX = Math.cos(radAngle) * distance;
      const offsetZ = Math.sin(radAngle) * distance;
      const targetLoc = new Vector3(player.location.x + offsetX, player.location.y, player.location.z + offsetZ)
      const entities = player.dimension.getEntities({
        location: targetLoc,
        maxDistance: 1,
      })
      entities.forEach(entity => {
        if (processedEntities.has(entity.id)) {
          return;
        }
        processedEntities.add(entity.id);
        pushEntity(entity, player.location);
      })
    }
  }
}

function pushEntity(entity, casterLocation) {
  if (entity.typeId == "blockception_magic:push_spell") {
    return;
  }
  const horizontalStrength = 1.75;
  const verticalStrength = 0.8;

  const directionX = entity.location.x - casterLocation.x;
  const directionZ = entity.location.z - casterLocation.z;
  const magnitude = Math.sqrt(directionX ** 2 + directionZ ** 2);
  if (magnitude > 0) {
    const impulse = new Vector3(
      (directionX / magnitude) * horizontalStrength,
      verticalStrength,
      (directionZ / magnitude) * horizontalStrength
    )
    entity.applyImpulse(impulse)
  }
}