---
-- @package   eg4-crank-ui
-- @file      component-logging.lua
-- @brief     Functionality related to changing the logging settings for components
--
-- @copyright Copyright 2024 Hanover Displays Limited.
-- @license   This program is the confidential and proprietary product of
--            Hanover Displays Limited. Any unauthorised use, reproduction or
--            transfer of this program is strictly prohibited. (Subject to
--            limited distribution and restricted disclosure only.) All
--            rights reserved.
--
--

-- local status data for this component
local info

---
--- @brief  Check if a logging mount point folder exists in this path
--- @return the mount point folder or nil if not found
local function GetLoggingMountPoint()
  local result = fileinfo:execute("ls -d1 /media/sd*/ 2>/dev/null")
  if #result > 0 then
    return result[1]
  end
end

---
--- @brief Callback to check whther the loggin menu item should be hidden
function CBCheckLoggingEnabled()
  gre.set_value("console_management_layer.menu_items.logging.grd_hidden", GetLoggingMountPoint() and 0 or 1)
end

---
--- @brief  Initialise the logging component list screen
--- @param  mapargs - the map arguments
function CBInitLogging(mapargs)
  info = {}
  info.mount_point = GetLoggingMountPoint()
  if info.mount_point == nil then
    TransitionBackScreen(mapargs)
    return
  end

  local ini_data = {}
  local filepath =  info.mount_point.."/hanover/"..sbsettings.get_sysinfo_product_id().."/logging.ini"
  if fileinfo:isfile(filepath) then
    ini_data = require("utils/ini-parser").load(filepath)
  end

  info.services = require("utils/scan-services").scan()

  for key,value in pairs(ini_data) do
    if info.services[key] then
      info.services[key] = ini_data[key]
    end
  end

  if not info.services["common"] then
    info.services["common"] = { log_folder = info.mount_point }
  end

  info.sorted_list = {}
  for service,_ in pairs(info.services) do
    if service ~= "common" then
      table.insert(info.sorted_list, service)
    end
  end
  table.sort(info.sorted_list, function(a,b) return a:lower() < b:lower() end)

  local group = "logging_layer.group"
  local control = group..".items"

  local data = {}
  for row,value in ipairs(info.sorted_list) do
    data[string.format(control..".text.%d.1", row)] = value
    data[string.format(control..".value.%d.1", row)] = info.services[value].debug_level or ""
    data[string.format(control..".checked.%d.1", row)] = info.services[value].enable_logging == 1 and 255 or 0
    data[string.format(control..".fade.%d.1", row)] = 0
  end
  data[group..".horizontal_divider.grd_y"] = #info.sorted_list * 81 - 1
  gre.set_table_attrs(control, { height = #info.sorted_list * 81, rows = #info.sorted_list })
  gre.set_data(data)
end

---
--- @brief  Set the logging level for the selected service
--- @param  value - the value of the logging level
--- @param  row - the row of the selected service
function set_logging(value, row)
  if info.services == nil then return end
  local service = info.sorted_list[row]
  if info.services[service] == nil then return end

  info.logging_updated = true

  info.services[service].enable_logging = value
  if value == 1 then
    info.services[service].debug_level = "debug"
  else
    info.services[service].debug_level = "info"
  end

  local group = "logging_layer.group"
  local control = group..".items"

  gre.set_value(string.format(control..".value.%d.1", row), info.services[service].debug_level or "" )
end

---
--- @brief  Save the logging settings to the logging.ini file and signal all processes to consume the new settings
function CBSaveLogging()
  if info.services == nil then return end

  if not info.logging_updated then return end

  for service, data in pairs(info.services) do
    if service ~= "common" and data.enable_logging == nil then
      info.services[service] = nil
    end
  end

  if info.mount_point == nil then return end
  if not fileinfo:isfolder(info.mount_point) then return end

  require("utils/ini-parser").save("/tmp/logging.ini", info.services)
  local folder = info.mount_point.."/hanover/"..sbsettings.get_sysinfo_product_id()
  os.execute("mount -o rw,remount "..info.mount_point.." ; mkdir -p "..folder.." ; cp /tmp/logging.ini "..folder.."/logging.ini")

  sbmodule.signal_all_processes()
end
