--[[
  @package eg4-crank-ui-2
  @file    serial-ports.lua
  @brief   Handles the serial port settings.
]]


local EDIT_SCREEN = "serial_port_edit"

local port_list_map = { count = 0 }
local cached_data = {}

---
--- @brief  Initialise the serial port list screen using the data received from the backend.
--- @param  gre#context mapargs
function cb_init_serial_port_setting_list_item(mapargs)
  local settings = loadstring(mapargs.context_event_data.text)()
  cached_data[settings.port_id] = settings

  local control = get_list_control(mapargs.context_screen)

  -- Determine if item is already present.
  local item = port_list_map[settings.port_id]

  if not item then
    -- Add the new item to the menu list.
    port_list_map.count = port_list_map.count + 1
    item = string.format(control..".%%s.%d.1", port_list_map.count)
    port_list_map[settings.port_id] = item

    local format = gre.get_value(control..".format")
    gre.set_value(string.format(item, "text"), string.format(format, settings.port_id))
    gre.set_value(string.format(item, "port_id"), settings.port_id)
    gre.set_value(string.format(item, "alpha_pressed"), 0)

    local height = gre.get_table_cell_attrs(control, 1, 1, "height").height
    gre.set_table_attrs(control, { height = port_list_map.count * height, rows = port_list_map.count })

    cb_update_menu(mapargs)
  end

  gre.set_value(string.format(item, "value"), sbsettings.get_serial_port_connection_linked_protocol(settings.port_id))
end

---
--- @brief  Initialise, and transition to, the serial port edit screen
--- @param  gre#context mapargs
function cb_serial_port_selected(mapargs)
  local item = string.format(mapargs.context_control..".%%s.%d.1", mapargs.context_row)
  gre.set_value(EDIT_SCREEN..".heading", gre.get_value(string.format(item, "text")))
  gre.set_value(EDIT_SCREEN..".port_id", gre.get_value(string.format(item, "port_id")))
  screen_transition(EDIT_SCREEN)
end

---
--- @brief  Get the serial port hardware for the specified port.
--- @param  port_id - port to query
--- @return string containing value.
function get_serial_port_hardware(port_id)
  return cached_data[port_id].hardware_group or "-"
end

---
--- @brief  Show/Hide flow control option depending on hardware.
--- @return true if option should be shown.
function show_serial_port_flow_control(screen)
  local port_id = gre.get_value(screen..".port_id")
  return cached_data[port_id].hardware_group == "RS232"
end
show_serial_port_flow_control_toggle = show_serial_port_flow_control

