--[[
  @package    eg4-crank-ui-2
  @file       list-item-select.lua
  @brief      Handles the general list item select screen
]]

local SCREEN = "general_item_select"

---
--- @brief  Populates the general list select screen with the list of files.
--- @param  gre#context mapargs
function cb_populate_file_list(mapargs)
  -- Collect the file path list
  local list = mapargs.context_event_data.text:lines()

  -- Sort the table (case insensitive)
  table.sort(list,
    function(a,b)
      return a:lower() < b:lower()
    end)

  -- Populate the selection screen
  local data = {}
  local control = get_list_control(SCREEN)
  for i,file_path in ipairs(list) do
    local items = file_path:split("/")
    data[control..".filepath."..i..".1"] = file_path
    data[control..".text."..i..".1"] = items[#items]
    data[control..".alpha_pressed."..i..".1"] = 0
    data[control..".more."..i..".1"] = 0
  end

  data[control..".grd_height"] = #list * gre.get_table_cell_attrs(control, 1, 1, "height").height
  gre.set_table_attrs(control, { rows = #list })

  data[SCREEN..".heading"] = mapargs.heading
  data[SCREEN..".selected_callback"] = mapargs.selected_callback
  data[SCREEN..".initialise_callback"] = "cb_update_menu"
  data[SCREEN..".cancelled_callback"] = mapargs.cancelled_callback

  gre.set_data(data)

  screen_transition(SCREEN)

  cb_set_mode_maintenance()
end
