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

export function createScoreboards() {
  //Spell slots 1-4
  if (!world.scoreboard.getObjective("bc_magic_sp1")) {
    world.scoreboard.addObjective("bc_magic_sp1", "bc.magic.sp1")
  }
  if (!world.scoreboard.getObjective("bc_magic_sp2")) {
    world.scoreboard.addObjective("bc_magic_sp2", "bc.magic.sp2")
  }
  if (!world.scoreboard.getObjective("bc_magic_sp3")) {
    world.scoreboard.addObjective("bc_magic_sp3", "bc.magic.sp3")
  }
  if (!world.scoreboard.getObjective("bc_magic_sp4")) {
    world.scoreboard.addObjective("bc_magic_sp4", "bc.magic.sp4")
  }
  //Active spell index
  if (!world.scoreboard.getObjective("bc_magic_asp")) {
    world.scoreboard.addObjective("bc_magic_asp", "bc.magic.asp")
  }
  //Locked spells
  if (!world.scoreboard.getObjective("bc_magic_lsp")) {
    world.scoreboard.addObjective("bc_magic_lsp", "bc.magic.lsp")
  }
  //Active spell slot
  if (!world.scoreboard.getObjective("bc_magic_asps")) {
    world.scoreboard.addObjective("bc_magic_asps", "bc.magic.asps")
  }
}

export function syncSpellLocked() {
  //For every spell
  for (let x = 2; x < spellsArray.length; x++) {
    //Check the score to see whether the spell is locked
    let scoreboardName = "spell" + x + ".locked"
    if (world.scoreboard.getObjective("bc_magic_lsp").getScore(scoreboardName) == 0) {
      //Sync locked status with spellsArray
      spellsArray[x].locked = false
    }
    //world.sendMessage(spellsArray[x].id + " - " + spellsArray[x].locked); //Debug
  }
}

//Getting scores from scoreboards
export function getScore(entity, name, defau = 0) {
  let score = world.scoreboard.getObjective(name);
  if (!score) {
      score = world.scoreboard.addObjective(name, name + ".score");
  }
  if (entity.scoreboardIdentity == undefined) {
      score.setScore(entity, defau);
      return defau;
  }
  let ret = score.getScore(entity);
  if (ret == undefined) {
      score.setScore(entity, defau);
      return defau;
  }
  return ret;
}
//Setting scores on scoreboards
export function setScore(entity, name, amt) {
  let score = world.scoreboard.getObjective(name);
  if (!score) {
      score = world.scoreboard.addObjective(name, name + ".score");
  }
  score.setScore(entity, amt);
}