---
-- @package   eg4-crank-ui
-- @file      ini-parser.lua
-- @brief     Loads and saves ini files.
--
-- @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 ini = {}

---
--- @brief  Load an ini file.
--- @param  filename - name of the file to load
--- @return table - the data from the ini file
function ini.load(filename)
  local file = io.open(filename, "r")
  if not file then return nil end

  local data = {}
  local section = nil
  for line in file:lines() do
    local temp = line:match("^%[([^%[%]]+)%]$")
    if temp then
      section = temp
      data[section] = data[section] or {}
    else
      local key, value = line:match("([^=]+)=(.*)")
      key = key:trim()
      if key and value then
        if tonumber(value) then
            value = tonumber(value)
        elseif value == "true" then
            value = true
        elseif value == "false" then
            value = false
        end
        if data[section] then
          if data[section][key] then
              data[section][key] = data[section][key].."\n"..value
          else
              data[section][key] = value
          end
        else
          if data[key] then
              data[key] = data[key].."\n"..value
          else
              data[key] = value
          end
        end
      end
    end
  end
  file:close()
  return data
end

--- @brief  Save an ini file.
--- @param  filename - name of the file to save
--- @param  data - the data to save
--- @return boolean - true if the file was saved
function ini.save(filename, data)
  local file = io.open(filename, "w")
  if not file then return end

  for k, v in pairs(data) do
    if type(v) ~= "table" then
      file:write(k.."="..tostring(v).."\n")
    end
  end

  for section, content in pairs(data) do
    if type(content) == "table" then
      file:write("["..section.."]\n")
      for k, v in pairs(content) do
        file:write(k.."="..tostring(v).."\n")
      end
    end
  end
  file:close()
  return true
end

return ini
