--[[
  @package    eg4-crank-ui-2
  @file       status-icons.lua
  @brief      Supports the status icons on the home screen.
]]

local GROUP = "status"
local COLS = 3
local ROWS = 2
local MAX_ICONS = COLS * ROWS
local X_START = 5
local X_OFFSET = 44
local Y_START = 6
local Y_OFFSET = 40

---
--- @brief  Get the list of status controls
--- @param  context_screen  The context screen
--- @return The list of status controls
local function get_status_control_list(context_screen)
  for _,layer in ipairs(context_screen:get_children() or {}) do
    layer = tostring(layer):object_name()
    if gre.get_value(layer.."."..GROUP..".grd_x") then
      return gredom.get_object(layer.."."..GROUP):get_children()
    end
 end
 return {}
end

---
--- @brief  Callback to update the status icon positions
--- @param  mapargs  The map arguments
function cb_update_status_icons(mapargs)
  local list = get_status_control_list(mapargs.context_screen)
  local count = 0
  local last
  for i = #list - 1,1,-1 do
    local item = list[i]
    if not item:get_hidden() then
      count = count + 1
      if count > MAX_ICONS then
        item:set_y(-100)
        if count == MAX_ICONS + 1 then
          last:set_y(-100)
        end
      else
        last = item
        item:set_position(X_START + ((count - 1) % COLS) * X_OFFSET, Y_START + math.floor((count - 1) / COLS) * Y_OFFSET)
      end
    end
  end
  -- Set the last item to show the number of hidden items
  list[#list]:set_hidden(count <= MAX_ICONS)
  list[#list]:set_value("text", string.format( "+%d", count - MAX_ICONS + 1))
end