-- 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 ports = Input

local net_ports = {}
for _, value in ipairs(ports) do
    if net_ports[value.NetworkAdapterId] == nil then
        net_ports[value.NetworkAdapterId] = {}
    end
    net_ports[value.NetworkAdapterId][value.PortID + 1] = value.LinkStatus
end

local history_info_str = ProcessingFlow[2].Destination.History


local history_info = cjson.json_object_ordered_decode(history_info_str)

local res = cjson.json_object_new_array()

for i, nic_history in ipairs(history_info) do
    local res_nic = cjson.json_object_new_object()
    local nic_id = nic_history.BWUWaveTitle
    res_nic.BWUWaveTitle = nic_id
    res_nic.CurrentUtilisePercents = cjson.json_object_new_array()
    for port, percent in ipairs(nic_history.CurrentUtilisePercents) do
        if net_ports[nic_id] and net_ports[nic_id][port] == 'LinkUp' then
            res_nic.CurrentUtilisePercents[port] = percent
        else
            res_nic.CurrentUtilisePercents[port] = cjson.null
        end
    end

    res_nic.UtilisePercents = cjson.json_object_new_array()
    for index, record in ipairs(nic_history.UtilisePercents) do
        local res_record = cjson.json_object_new_object()
        res_record.Time = record.Time
        local key
        for k, v in ipairs(record.UtilisePercent) do
            key = string.format('Port%sUtilisePercents', k)
            res_record[key] = v
        end
        res_nic.UtilisePercents[index] = res_record
    end

    res[i] = res_nic
end

return res