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

const playerCooldowns = new Map();

export function getCooldown(player, spellID) {
  let spellName = spellsArray[spellID].id;
  if (!playerCooldowns.has(player.id)) {
    return -1;
  };
  let playerSpells = playerCooldowns.get(player.id);
  if (!playerSpells.has(spellName)) {
    return -1;
  };
  return playerSpells.get(spellName);
};

export function setCooldown(player, spellID) {
  const playerId = player.id;
  const cooldownTime = spellsArray[spellID].cooldown * 20;
  const spellName = spellsArray[spellID].id;
  //If player has no cooldowns create map
  if (!playerCooldowns.has(playerId)) {
    playerCooldowns.set(playerId, new Map());
  }
  const playerSpells = playerCooldowns.get(playerId);

  //If spell has existing cooldown
  if (playerSpells.has(spellName)) {
    const remainingCooldown = playerSpells.get(spellName);
    if (remainingCooldown > 0) {
      return;
    }
  }
  //Set cooldown
  playerSpells.set(spellName, cooldownTime);
};

export function tickCooldowns() {
  playerCooldowns.forEach((spells, playerId) => {
    spells.forEach((time, spellName) => {
      if (time > 0) {
        spells.set(spellName, time - 1);
      } else {
        spells.delete(spellName)
      }
    });
    if (spells.size === 0) {
      playerCooldowns.delete(playerId);
    }
  });
};

