import { world, EffectTypes } from "@minecraft/server";
import { Vector3 } from "../Vector3";
import { spawnParticle } from "../SpawnParticle";

const shieldMap = new Map();

//Function run when using the spell
export function shieldSpell(player) {
  const dimension = player.dimension;
  player.sendMessage(`<${player.nameTag}> Shielding spell!`);
  //Effect
  player.addEffect(EffectTypes.get('resistance'), 150, {amplifier: 5, showParticles: false});
  player.addEffect(EffectTypes.get('slowness'), 150, {amplifier: 1, showParticles: false});
  let shield = world.getDimension(dimension.id).spawnEntity('blockception_magic:magic_shield', player.location);
  shieldMap.set(shield.id, {player, shield});
}

export function shieldTick() {
  shieldMap.forEach(({player, shield}) => {
    if (shield && shield.isValid() && player && player.isValid()) {
      const playerYaw = player.getRotation().y;
      const radYaw = (playerYaw + 90) * (Math.PI / 180);

      const tpPos = new Vector3(
        player.location.x + (Math.cos(radYaw) * 1.25),
        player.location.y + 0.5,
        player.location.z + (Math.sin(radYaw) * 1.25)
      );
      shield.teleport(tpPos, {
        dimension: player.dimension, 
        rotation: player.getRotation(),
      });
    } else {
      shieldMap.delete(shield.id);
    }
  })
}