-- 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 m = {}

local function get_position_by_id(id)
    local id_table = {}
    for w in string.gmatch(id, '[^_]+') do
        table.insert(id_table, w)
    end
    return id_table[#id_table]
end

local function get_tbl_num(tbl)
    local count = 0
    for _, _ in pairs(tbl) do
        count = count + 1
    end
    return count
end

local function get_logic_version_tbl(multilogicversion)
    if not multilogicversion or
        not cjson.json_object_is_object(multilogicversion) and
        not cjson.json_object_is_array(multilogicversion) then
        return {}, {}
    end
    local multi_logic_version = {}
    local fpga_version = {}
    for key, value in pairs(multilogicversion) do
        if string.match(key, "FPGA") then
            fpga_version[key] = value
            goto continue
        end
        multi_logic_version[key] = value
        ::continue::
    end
    return multi_logic_version, fpga_version
end

function m.get_extend_info(type, board_obj, object_identifier, firmware_paths, model)
    local mcus = {}
    for _, v in ipairs(firmware_paths) do
        if string.find(v, 'MCU_') then
            local obj = mdb.get_object(bus, v, 'bmc.kepler.UpdateService.FirmwareInfo')
            local Position = get_position_by_id(obj.Id)
            mcus[Position] = obj.Version
        end
    end

    local body = {}
    body.PartNumber = board_obj.PartNumber
    body.PCBVersion = board_obj.PcbVersion
    body.SerialNumber = board_obj.SerialNumber

    local multi_logic_version, fpga_version = get_logic_version_tbl(board_obj.MultiLogicVersion)

    if get_tbl_num(multi_logic_version) > 1 then
        for k, v in pairs(multi_logic_version) do
            body[k .. "Version"] = v
        end
    else
        body.CPLDVersion = board_obj.LogicVersion
    end

    for k, v in pairs(fpga_version) do
        body[k .. "Version"] = v
    end

    body.HWSRVersion = board_obj.SRVersion

    if type == 'NpuBoard' then
        body.NpuName = model
    end

    if object_identifier and mcus[object_identifier[4]] then
        body.McuVersion = mcus[object_identifier[4]] or ''
    end
    return body
end

return m
