local storage = core.get_mod_storage()

local function unlock_default_skills() end
local function remove_deprecated_equipment() end

local p_data = {}      -- KEY: p_name, INDEX: {equip = {weapons = {...}, skill = s_name}}

local DEFAULT_WEAPONS = {"block_league:smg", "block_league:sword", "block_league:pixelgun"}
local DEFAULT_SKILL   = "block_league:hp"



function block_league.load_player_data(p_name)
  -- primo accesso
  if storage:get_string(p_name) == "" then
    unlock_default_skills(p_name)

    p_data[p_name] = {}
    p_data[p_name].equip = {}

    block_league.set_player_weapons(p_name, DEFAULT_WEAPONS)
    block_league.set_player_skill(p_name, DEFAULT_SKILL)
    p_data[p_name] = {equip = { weapons = DEFAULT_WEAPONS, skill = DEFAULT_SKILL}} -- this line will become useless once custom weapons are implemented
    storage:set_string(p_name, core.serialize(p_data[p_name]))

  -- sennò carica
  else
    -- inserire qui nuove abilità da sbloccare automaticamente

    -- in case skills' database has been reset
    if not next(p_name:get_unlocked_skills("block_league")) then
      unlock_default_skills(p_name)
    end

    p_data[p_name] = core.deserialize(storage:get_string(p_name))

    remove_deprecated_equipment(p_name, p_data[p_name].equip)

    block_league.set_player_weapons(p_name, p_data[p_name].equip.weapons)
    block_league.set_player_skill(p_name, p_data[p_name].equip.skill)
  end
end



-- appunti per il futuro:
-- 1. meglio tenere `type` e `param`, dato che si allacceranno armi, abilità,
-- esperienza e valuta della mod;
-- 2. meglio evitare di fare un pastone in una classe enorme, col rischio di
-- creare confusione. Meglio un po' più di ridondanza nelle funzioni (es. x
-- salvare abilità: set_skill -> update_storage, piuttosto che tutto qui dentro)
function block_league.update_storage(p_name, type, param)
  if type == "weapons" then
    p_data[p_name].equip.weapons = param
  elseif type == "skill" then
    p_data[p_name].equip.skill = param
  end

  storage:set_string( p_name, core.serialize(p_data[p_name]))
end



function block_league.is_player_in_storage(p_name)
  return storage:get_string(p_name) ~= ""
end





----------------------------------------------
---------------FUNZIONI LOCALI----------------
----------------------------------------------

function unlock_default_skills(p_name)
  p_name:unlock_skill("block_league:hp")
  p_name:unlock_skill("block_league:sp")
  p_name:get_skill("block_league:hp"):disable()
  p_name:get_skill("block_league:sp"):disable()
end



function remove_deprecated_equipment(p_name, equip)
  local to_update = false

  for i, w_name in ipairs(equip.weapons) do
    if w_name == "block_league:kunai" then
      equip.weapons[i] = "block_league:sentry_gun"
      to_update = true
    end
  end

  if to_update then
    block_league.update_storage(p_name, "weapons", equip.weapons)
  end
end