-- 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 log = require 'mc.logging'
local cjson = require 'cjson'
local mdb_service = require 'mc.mdb.mdb_service'
local m = {}

local VLANS_INTERFACE<const> = 'bmc.kepler.Systems.NetworkPort'
-- GetPath函数返回的无效路径
local INVALID_PATH<const> = ''

function m.get_ethname(path)
    local network_adapter_id = string.match(string.lower(path), '([^/]*)port%d+')
    local port_id = string.match(string.lower(path), '.*port(%d+)') - 1
    local filter = {
        NetworkAdapterId = network_adapter_id,
        PortID = port_id
    }
    local res, rsp = pcall(mdb_service.get_path, bus, VLANS_INTERFACE, cjson.encode(filter), true)
    if not res then
        return nil
    end

    local ok, obj = pcall(mdb.get_object, bus, rsp.Path, VLANS_INTERFACE)
    if not ok then
        return nil
    end
    return obj.Name
end

function m.get_ethnames(paths)
    local ethnames = {}
    for _, path in ipairs(paths) do
        ethnames[#ethnames + 1] = m.get_ethname(path)
    end

    return cjson.encode(ethnames)
end

function m.get_bonded_Interfaces(links)
    local bonded_interfaces = {}

    if links.BondedInterfaces then
        for _, obj in pairs(links.BondedInterfaces) do
            for _, value in pairs(obj) do
                bonded_interfaces[#bonded_interfaces + 1] = value
            end
        end
    end
    return bonded_interfaces
end

function m.get_creatbond_req(req_obj)
    req_obj.WorkMode = tostring(req_obj.BondingType)
    req_obj.BondingType = nil
    req_obj.MIILinkMonitoringFrequencyMS = tostring(req_obj.MIILinkMonitoringFrequencyMS)

    if req_obj.Links then
        local bonded_interfaces = m.get_bonded_Interfaces(req_obj.Links)

        local ok, ethnames = pcall(m.get_ethnames, bonded_interfaces)
        if not ok then
            log:error("Get ethnames failed, err: %s", ethnames)
            ethnames = '[]'
        end
        req_obj.Ports = ethnames
        req_obj.Links = nil
    end

    if req_obj.IsOnBoot ~= nil then
        req_obj.OnBoot = req_obj.IsOnBoot and "yes" or "no"
        req_obj.IsOnBoot = nil
    end
    return req_obj
end

return m
