--[[
  @package   eg4-crank-ui-2
  @file      table-utils.lua
  @brief     Extra table utilities extending table class
]]

---
--- @brief  Copies a table
--- @param  src - The table to copy
--- @return The copied table
function table.copy(src)
  local dst = {}
  for k, v in pairs(src) do
    if type(v) == "table" then
      dst[k] = table.copy(v)
    else
      dst[k] = v
    end
  end
  return dst
end

---
--- @brief  Merges 2 tables
--- @param  src - The table to copy
--- @param  dst - The table to copy into
--- @return The copied table
function table.merge(dst, src)
  local dst = (type(dst) == 'table') and dst or {}
  for k, v in pairs(src) do
    if type(v) == "table" then
      dst[k] = table.merge(dst[k], v)
    else
      dst[k] = v
    end
  end
  return dst
end

---
--- @brief  Add defaults to table
--- @param  dst - Table to add defaults to
--- @param  src - Table containing the defaults
--- @return The copied table
function table.add_defaults(dst, src)
  if dst == nil then return src end
  for k, v in pairs(src) do
    if type(v) == "table" then
      dst[k] = table.add_defaults(dst[k], v)
    elseif type(v) ~= type(dst[k]) then
      dst[k] = v
    end
  end
  return dst
end

--- @brief  Checks if a table contains an element
--- @param  table - The table to check
--- @param  element - The element to check for
--- @return index of item, or nil
function table.find(table, element)
  for k, v in pairs(table) do
    if v == element then
      return k
    end
  end
  return nil
end

---
--- @brief  Sort map pairs by key value and return iterator
--- @param  t - The table to sort
--- @param  f - The sort function
--- @return The iterator
function sorted_pairs(t, f)
  local a = {}
  for n in pairs(t) do
    table.insert(a, n)
  end

  table.sort(a, f)

  local i = 0
  return function ()
    i = i + 1
    if a[i] == nil then
      return nil
    else
      return a[i], t[a[i]]
    end
  end
end


--- Test lua version to include missing table pack/unpack functions
if _VERSION < "Lua 5.2" then
  ---
  --- @brief  pack function for Lua 5.1
  --- @param  ... - The list to pack
  --- @return The packed table
  table.pack = table.pack or function(...)
    return { n = select("#", ...), ... }
  end

  ---
  --- @brief  table.unpack function for Lua 5.1
  table.unpack = table.unpack or unpack
end
