import { world, EquipmentSlot } from "@minecraft/server";
import { spellsArray } from "./Spells/SpellsList";

//Using spell tomes
export function tomeUse(player, item) {
  const itemID = item.typeId;
  let tomeName = itemID.split("blockception_magic:tome_")[1];
  for (let spell in spellsArray) {
    if (spellsArray[spell].id == tomeName) {
      tomeUnlocked(spell, player);
    };
  };
}

function tomeUnlocked(x, player) {
  if (!spellsArray[x].locked) {
    player.sendMessage("You already know this spell! Equip it at the §6sorcery table§r.");
    return;
  }
  if (spellsArray[x].locked) {
    world.sendMessage("§6" + spellsArray[x].displayName + "§r spell unlocked! Equip it at the §6sorcery table§r.");
    //Unlock the spell on the back end
    spellsArray[x].locked = false;
    let scoreboardName = "spell" + x + ".locked";
    world.scoreboard.getObjective("bc_magic_lsp").setScore(scoreboardName, 0);
    //Clear item
    const itemName = "blockception_magic:tome_" + spellsArray[x].id.toLowerCase();
    const item = player.getComponent("equippable").getEquipmentSlot(EquipmentSlot.Mainhand);
    if (item.amount == 1) {
      item.setItem();
    } else {
      --slot.amount;
    }
    world.getDimension("overworld").runCommand("/execute as @a[hasitem={item=" + itemName + ",location=slot.weapon.mainhand,slot=0}] at @s run clear @s " + itemName + " 1");
    //Play sound
    let soundName = "tome." + spellsArray[x].id;
    player.dimension.playSound(soundName, player.location);
  }
}