-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.


local log = require 'mc.logging'
local ini_parser = require 'mc.v2_persistence'

local parser_cfg = {}

local function split_string_by_comma(str)
    if not str or str == '' then
        return {}
    end
    
    local result = {}
    for item in string.gmatch(str, '([^,]+)') do
        -- 去除前后空格
        local trimmed = item:match("^%s*(.-)%s*$")
        if trimmed and trimmed ~= '' then
            table.insert(result, trimmed)
        end
    end
    
    return result
end

local function cfg_new(name, data)
    local cfg = {
        name = name,
        component_id = tonumber(data.ComponentID),
        component_idex = tonumber(data.ComponentIDEx),
        model = split_string_by_comma(data.Model)
    }
    return cfg
end

function parser_cfg.parse_dir(file_path)
    local s, e = string.find(file_path, "/.+/")
    local dir = string.sub(file_path, s, e)
    local firmware_name = string.sub(file_path, e + 1, -1)
    return dir, firmware_name
end

-- prepare阶段框架会下发解包的update.cfg路径，解析文件内容，获取每个Firmware的配置
function parser_cfg.get_cfgs(path)
    local cfgs = {}
    if not path then
        log:error("Cfg path is nil")
        return cfgs
    end

    log:info("get cfg path=%s", path)
    local data = ini_parser.load_file(path)
    if not data.Basic or not data.Basic.Version then
        log:error('Get Basic Version failed')
        return cfgs
    end
    local file_num = tonumber(data.Firmware.FileNum)
    if file_num == 0 then
        log:error('Update file num is invalid')
        return cfgs
    end
    for i = 1, file_num - 1 do -- 第1个Firmware指的就是配置文件，从1开始
        local name = 'Firmware' .. i
        if data[name] then
            cfgs[name] = cfg_new(name, data[name])
            log:info("Get Firmware, name=%s", name)
        end
    end
    return cfgs
end

return parser_cfg