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

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

export function poisonHurtSpellEvent(location, dimension) {
  //Get entities within 2.5 blocks
  const entities = world.getDimension(dimension.id).getEntities({
    location: location,
    maxDistance: 2.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);
    }
  };
  //Area Particles
  spawnParticle("blockception_magic:poison_area", location, dimension);
  spawnParticle("blockception_magic:poison_area_fog", location, dimension);
  spawnParticle("blockception_magic:poison_ring", location, dimension);
  //Apply effect to each entity
  entities.forEach(entity => {
    if (entity.typeId == undefined) {
      return;
    }
    if (entity.typeId == "minecraft:player" || entity.typeId == "minecraft:wither_skeleton") {
      entity.addEffect(EffectTypes.get('poison'), 200, {amplifier: 1, showParticles: false});
      entity.addEffect(EffectTypes.get('nausea'), 200, {amplifier: 1, showParticles: false});
    }
    entity.addEffect(EffectTypes.get('wither'), 200, {amplifier: 1, showParticles: false});
  })
}