-- 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 NET_TYPE_LOM = 1
local NET_TYPE_LOM2 = 5
local NET_DEV_FUNC_TYPE_FC = 2
local UB_MODEL = "NPU_UB"

local netcard_slot_cmp = function (netcard_1, netcard_2)
    if netcard_1.PcieSlotId > netcard_2.PcieSlotId then
        return false
    end
    if netcard_1.PcieSlotId == netcard_2.PcieSlotId and netcard_1.Type >= netcard_2.Type then
        return false
    end
    return true
end

local netcard_cmp = function (netcard_1, netcard_2)
    if netcard_1.Type == NET_TYPE_LOM then
        if netcard_2.Type == NET_TYPE_LOM then
            return netcard_slot_cmp(netcard_1, netcard_2)
        end
        return true
    end
    if netcard_1.Type == NET_TYPE_LOM2 then
        if netcard_2.Type == NET_TYPE_LOM then
            return false
        elseif netcard_2.Type == NET_TYPE_LOM2 then
            return netcard_slot_cmp(netcard_1, netcard_2)
        end
        return true
    end
    if netcard_2.Type == NET_TYPE_LOM or netcard_2.Type == NET_TYPE_LOM2 then 
        return false
    end
    return netcard_slot_cmp(netcard_1, netcard_2)
end

local netcard_table = cjson.json_object_new_array()
for i in pairs(Input) do
    if Input[i].NetDevFuncCapabilities == NET_DEV_FUNC_TYPE_FC then
        goto continue
    end
    if Input[i].Type == 6 or Input[i].Type == 7 or Input[i].Type == 8 then
        goto continue
    end
    if Input[i].Name and string.find(Input[i].Name, 'ROH') then
        goto continue
    end
    if Input[i].Model and Input[i].Model == UB_MODEL then
        goto continue
    end
    netcard_table[#netcard_table + 1] = Input[i]
    ::continue::
end

for i = 1, #netcard_table, 1 do
    for j = 1, #netcard_table - i, 1 do
        if not netcard_cmp(netcard_table[j], netcard_table[j + 1]) then
            netcard_table[j], netcard_table[j + 1] = netcard_table[j + 1], netcard_table[j]
        end
    end
end

for i in pairs(netcard_table) do
    if netcard_table[i].Type == NET_TYPE_LOM or netcard_table[i].Type == NET_TYPE_LOM2 then
        netcard_table[i].PcieSlotId = null
    end
    netcard_table[i].Type = nil
end

return netcard_table