import { world} from "@minecraft/server"

export function getScore(player, objective) {
    try {
      const s = world.scoreboard.getObjective(objective);
      if (!s) world.scoreboard.addObjective(objective, objective);
      return s.getScore(player.scoreboardIdentity);
    } catch {
      return 0;
    }
   }
  

const startScoreboard =
[
  { id: "Spear_use_time", value: 0 },
  {id:"Summoned_entity_number",value:0},
  {id:"summoning_cooldown_score",value:0},
  {id:"max_health",value:20},
  {id:"magic_axe",value:0},
  {id:"difficulty2",value:0},
  {id:"difficulty",value:0},
  {id:"light",value:0},
  {id:"void",value:0},
  {id:"speed",value:0},
  {id:"Bramble",value:0},
  {id:"Sculk_portal",value:0},
  {id:"mode",value:0},
  {id:"dash",value:0},
  {id:"Height",value:0},
  {id:"Fire_breath",value:0},
  {id:"Liver_break",value:0},
  {id:"Married_soul",value:0},
  {id:"Hit_cooldown",value:0},
  {id:"Sneak_time",value:0},
  {id:"Dreamlike_pendant",value:0},
  {id:"Chaining",value:0},
  {id:"start",value:0},
  {id:"Bow",value:0},
  {id:"shield",value:0},
  {id:"Void_cloak",value:0},
  {id:"Battle_cry",value:0},
  {id:"Wither_ribs",value:0},
  {id:"oxidise"},//just create the scoreboard
]

const timerScoreboard =
[
  { id: "Spear_use_time", addTag: "", removeTag: "" },
  {id:"summoning_cooldown_score",addTag:"",removeTag:""},
  {id:"magic_axe",addTag:"",removeTag:""},
  {id:"Dreamlike_pendant",addTag:"",removeTag:""},
  {id:"Liver_break",addTag:"Liver_break",removeTag:"Liver_break"},
  {id:"Married_soul",addTag:"",removeTag:"already_soul_mirror"},
  {id:"Sneak_time",addTag:"",removeTag:""},
  {id:"dash",addTag:"",removeTag:""},
  {id:"shield",addTag:"",removeTag:""},
  {id:"Bramble",addTag:"",removeTag:""},
  {id:"Battle_cry",addTag:"",removeTag:""},
  {id:"Void_cloak",addTag:"",removeTag:""},
  {id:"Wither_ribs",addTag:"",removeTag:""},
  {id:"Sculk_portal",addTag:"",removeTag:""}
]

export function TimerScoreboard5Ticks(player)
{
  timerScoreboard.forEach(scoreboard => {
    const score = world.scoreboard.getObjective(scoreboard.id);
    if(score.getScore(player)>=1)
    {
      if(!player.hasTag(scoreboard.addTag))
      {
        player.addTag(scoreboard.addTag)
      }
      if(scoreboard.id=="Spear_use_time" && score.getScore(player) ==1)
      {
        player.triggerEvent("knockback")
      }
      score.addScore(player, -1)
      if(score.getScore(player)<=0 && player.hasTag(scoreboard.removeTag))
      {
            player.removeTag(scoreboard.removeTag)
      }
    }
  });
}


export function SetStartScoreboards(player)
{
  startScoreboard.forEach(scoreboard => {
    const objective =scoreboard.id
    var s = world.scoreboard.getObjective(objective);
    if (!s) {
      world.scoreboard.addObjective(objective, objective);
      s = world.scoreboard.getObjective(objective);
    }
    if(s?.getScore(player)==undefined && scoreboard?.value!=undefined)
      s.setScore(player,scoreboard.value)
  })
}