import { world, EffectTypes } from "@minecraft/server";
import { castSpellProjectile } from "./Spells";
import { mobList } from "./MobList";
import { spawnParticle } from "../SpawnParticle";

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

export function transformHurtSpellEvent(entity) {
  //Check that it is a transformable mob
  const entityID = entity.typeId;
  if (!(entityID in mobList)) {
    return;
  }
  //Stop the entity from moving
  entity.addEffect(EffectTypes.get('slowness'), 100, {amplifier: 255, showParticles: false});
  //Get the family of the entity
  const family = mobList[entityID].family;
  //Get the items around the entity
  const items = entity.dimension.getEntities({
    location: entity.location,
    maxDistance: 4,
    type: 'minecraft:item'
  })
  const entityLocation = entity.location;
  const dimension = entity.dimension;

  for (let itemEntity of items) {
    const itemType = itemEntity.getComponent("minecraft:item").itemStack.typeId;
    if (itemType == undefined) {
      return;
    }
    for (let mob in mobList) {
      const mobData = mobList[mob];
      if (!mobData.transfigurable) {
        continue;
      };
      if (mobData.items.includes(itemType)) {
        if (mobData.family == family) {
          let name = entity.nameTag;
          //Particles
          spawnParticle("blockception_magic:transform_item", itemEntity.location, itemEntity.dimension);
          spawnParticle("blockception_magic:transform_item_fog", itemEntity.location, itemEntity.dimension);
          spawnParticle("blockception_magic:transform_mob", entity.location, entity.dimension);
          spawnParticle("blockception_magic:transform_mob_fog", entity.location, entity.dimension);
          entity.teleport({x: entityLocation.x, y: -100, z: entityLocation.z});
          itemEntity.teleport({x: entityLocation.x, y: -100, z: entityLocation.z});
          let newEntity = dimension.spawnEntity(mob, entityLocation);
          if (name) {
            newEntity.nameTag = name;
          }
          break;
        }
      }
    }
    break;
  }
}