local ItemUtils = {}

local datasutils = require "game.utils.datas"

local DIR = "items"

function ItemUtils.getBaseDirectory(lua)
  return datasutils.concatDataFolder(DIR, lua)
end

function ItemUtils.listCategories()
  return require(ItemUtils.getBaseDirectory(true))
end

function ItemUtils.getCategoryDirectory(directory, lua)
  return datasutils.concatFolder(ItemUtils.getBaseDirectory(lua), directory, lua)
end

function ItemUtils.getItemsFromCategory(directory)
  local folder = ItemUtils.getCategoryDirectory(directory, false)
  local baseTable = love.filesystem.getDirectoryItems(folder)
  return datasutils.luaFileListToModuleList(baseTable)
end

function ItemUtils.getItemFile(category, item, lua)
  local dir = ItemUtils.getCategoryDirectory(category, lua)
  local path = datasutils.concatFolder(dir, item, lua)
  if (not lua) then
    path = path .. ".lua"
  end
  return path
end

function ItemUtils.itemExists(category, item)
  local path = ItemUtils.getItemFile(category, item, false)
  local fileinfo = love.filesystem.getInfo(path)
  return (fileinfo ~= nil)
end

function ItemUtils.getItemData(category, item)
  local path = ItemUtils.getItemFile(category, item, true)
  return datasutils.copy(path)
end

-- VALIDATION FUNCTIONS

function ItemUtils.getItemEffectStructure(type)
  local typeList = require "game.utils.items.arguments"
  return typeList[type]
end

function ItemUtils.itemEffectExists(type)
  return (ItemUtils.getItemEffectStructure(type) ~= nil)
end

function ItemUtils.validateItemEffect(effectBaseData)
  local structure = ItemUtils.getItemEffectStructure(effectBaseData[1])
  if (structure == nil) then
    return false
  else
    return ((#structure + 1) == #effectBaseData)
  end
end

function ItemUtils.getItemEffectData(effectBaseData)
  local effectData = {}
  effectData.type = effectBaseData[1]

  if (ItemUtils.validateItemEffect(effectBaseData)) then
    local structure = ItemUtils.getItemEffectStructure(effectData.type)

    for i, argumentName in ipairs(structure) do
      local argumentContent = effectBaseData[i + 1]
      effectData[argumentName] = argumentContent
    end

    return effectData
  else
    error("Le type d'effet d'objet " .. effectData.type .. " à un nbr d'argument incorrect")
  end
end

return ItemUtils
