-- 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 cjson = require 'cjson'

local ODATA_ID <const> = "@odata.id"
local SYSTEM_ID<const> = 1

local m = {}

local URL_MAP = {
    ['CPU']               = '/redfish/v1/Systems/%s/Processors/%s',
    ['Memory']            = '/redfish/v1/Systems/%s/Memory/%s',
    ['NetworkAdapter']     = '/redfish/v1/Chassis/%s/NetworkAdapters/%s',
}

local function get_system_id()
    return SYSTEM_ID
end

local function get_odata_id(obj)
    local url_pattern = URL_MAP[obj.Type]
    local id
    if obj.Type == 'CPU' then
        id = string.match(obj.Name, '%d+')
        return string.format(url_pattern, get_system_id(), tostring(id))
    elseif obj.Type == 'Memory' then
        return string.format(url_pattern, get_system_id(), obj.Name)
    elseif obj.Type == 'NetworkAdapter' then
        return string.format(url_pattern, get_system_id(), string.gsub(obj.Name, " ", ""))
    else
        return cjson.null
    end
end

function m.get_result(data_list)
    if not data_list or #data_list == 0 then
        return {}
    end
    local res = cjson.json_object_ordered_decode(data_list)
    local results = cjson.json_object_new_array()
    for i = 1, #res, 1 do
        local asset_item = cjson.json_object_new_object()
        local data_item = cjson.json_object_new_object()
        asset_item.Name = res[i].Name
        asset_item[ODATA_ID] = get_odata_id(res[i])

        data_item.Type = res[i].Type
        data_item.Description = res[i].Description
        data_item.StandardDescription = res[i].StandardDescription
        data_item.ActualDigest = res[i].ActualDigest
        data_item.StandardDigest = res[i].StandardDigest

        asset_item.Data = data_item
        results[#results + 1] = asset_item
    end
    return results
end

return m
