--[[
  @package    eg4-crank-ui-2
  @file       tabs.lua
  @brief      Handles the tabs group in the heading layer
]]

---
--- @brief  Selects the specified tab
--- @param  context_group - the group containing the tabs
--- @param  context_control - the tab to select
local function select_tab(context_group, context_control)
  local list = get_children(context_group)
  local data = {}
  local context_screen = gre.env("active_screen")
  for i = 1, #list do
    local control = tostring(list[i])
    local selected = control == context_control
    data[control..".selected_alpha"] = selected and 255 or 0
    data[control..".grd_active"] = not selected
    local layer = control:object_name().."_layer"
    gre.set_layer_attrs_global(layer, { hidden = not selected })
    local font = gre.get_value("font_regular")
    local size = gre.get_value(control..".font_size")
    local text = gre.get_value(control..".text")
    local width = gre.get_string_size(font, size, text).width
    data[control..".width"] = width
  end
  gre.set_data(data)
end

---
--- @brief  Callback to selects the specified tab
--- @param  mapargs callback context
function cb_select_tab(mapargs)
  select_tab(mapargs.context_group, mapargs.context_control)
end

---
--- @brief  Find the tabs layer on the context screen
--- @param  context_screen - the screen to search
--- @return The layer name or nil if not found
local function find_tabs(context_screen)
  local list = get_children(context_screen)
  local data = {}
  for i = 1, #list do
    local layer = tostring(list[i])
    if gre.get_value(layer..".tabs.grd_active") ~= nil then
      return layer:object_name()
    end
  end
end

---
--- @brief  Reset the tabs to the first tab
--- @param  context_layer - the layer containing the tabs
local function reset_tabs(context_layer)
  if not context_layer then return end
  local list = gredom.get_object(context_layer..".tabs"):get_children()
  context_control = tostring(list[#list])
  select_tab(context_layer..".tabs", context_control)
end

---
--- @brief  Callback to reset the tabs
--- @param  mapargs callback context
function cb_reset_tabs(mapargs)
  reset_tabs(find_tabs(mapargs.context_screen))
end