-- Copyright (c) 2025 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 network_port_sum = {}

-- 工具函数：处理字段值的有效性转换
local function get_valid_field_value(field_value)
    local valid_value = 0
    if field_value ~= nil then
        if type(field_value) == "string" then
            valid_value = field_value == "" and 0 or (tonumber(field_value) or 0)
        end
    end
    return valid_value
end

function network_port_sum.sum_port_frames_by_field(port_path_list, field_name)
    local total = 0
    if not port_path_list or type(port_path_list) ~= "table" then
        return total
    end
    if not field_name or type(field_name) ~= "string" then
        return total
    end
    local ok, metrics_obj
    for _, port_path in pairs(port_path_list) do
        if port_path and port_path ~= "" then
            ok, metrics_obj = pcall(mdb.get_object, bus, port_path, 'bmc.kepler.Systems.NetworkPort.Metrics')
            if ok then
                total = total + get_valid_field_value(metrics_obj[field_name])
            end
        end
    end
    return total
end

return network_port_sum