import { world, system, EffectTypes } from "@minecraft/server";
import { castSpellProjectile } from "./Spells";
import { namespace } from "../Namespace";
import { spawnParticle } from "../SpawnParticle";

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

export function levitatingHurtSpellEvent(location, dimension) {
  //Get entities within 2.5 blocks
  const entities = world.getDimension(dimension.id).getEntities({
    location: location,
    maxDistance: 3.5,
  });
  //Remove any undefined entities or other spells nearby
  for ( let x = entities.length - 1; x >= 0; x-- ) {
    if (entities[x] === undefined) {
      entities.splice(x, 1);
    }
    if (entities[x].typeId.startsWith(namespace) && entities[x].typeId.endsWith("_spell")) {
      entities.splice(x, 1);
    }
  };
  //Apply effects to the entities
  entities.forEach(entity => {
    entity.addEffect(EffectTypes.get('levitation'), 120, {amplifier: 2, showParticles: false});
    spawnParticle("blockception_magic:levitation_spell", entity.location, entity.dimension);
    spawnParticle("blockception_magic:levitation_spell_fog", entity.location, entity.dimension);
    if (entity.typeId == "minecraft:player") {
      return;
    }
    system.runTimeout(() => {
      try {
        entity.applyImpulse({x: 0, y: -5, z: 0})
      }
      catch (e) { }
    }, 120);
  });
}