-- 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 m = {}

local function get_media_type(MediumType)
    if MediumType == 'Copper' then
        return 'Electrical'
    elseif MediumType == 'FiberOptic' then
        return 'Optical'
    else
        return ''
    end
end

local function get_linkstatus(obj)
    local os_link_status = obj.OSLinkStatus
    local link_status = obj.LinkStatus
    local name = obj.Name

    if name and #name ~= 0 then
        if os_link_status and #os_link_status ~= 0 then
            return os_link_status
        else
            if link_status == "Disconnected" then
                return "NoLink"
            else
                return null
            end
        end
    else
        if link_status == "Disconnected" then
            return "Down"
        elseif link_status == "Connected" then
            return "Up"
        else
            return null
        end
    end
end

function m.get_simple_portproperties(paths)
    local port_properties = cjson.json_object_new_array()
    for _, path in pairs(paths) do
        local basic_attribute_info = cjson.json_object_new_object()
        local ok, obj = pcall(mdb.get_object, bus, path, 'bmc.kepler.Systems.NetworkPort')
        if ok and obj then
            basic_attribute_info.PhysicalPortNumber = obj.PortID + 1
            basic_attribute_info.LinkStatus = get_linkstatus(obj)
            basic_attribute_info.MediaType = get_media_type(obj.MediumType)
            basic_attribute_info.InterfaceType = obj.FunctionType
            basic_attribute_info.Name = obj.Name
        end
        ok, obj = pcall(mdb.get_object, bus, path, 'bmc.kepler.Systems.NetworkPort.FibreChannel')
        if ok and obj then
            basic_attribute_info.FC_ID = obj.FCId
        end
        port_properties[#port_properties + 1] = basic_attribute_info
    end
    return port_properties
end

function m.get_portid(paths, portnum)
    for _, path in pairs(paths) do
        local ok, obj = pcall(mdb.get_object, bus, path, 'bmc.kepler.Systems.NetworkPort')
        if ok and obj and obj.PortID == portnum - 1 then
            obj = mdb.get_object(bus, path, 'bmc.kepler.Object.Properties')
            return obj.ObjectName
        end
    end
end

return m