-- 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 class = require 'mc.class'
local c_base = require 'biz_topo.class.base'

---@class BusinessConnector: Base @业务TOPO连接器
---@field public mds_obj table @MDS对象
---@field public configs BDFConfiguration[] @端口
local c_bdf_config = class(c_base)

local function config_new(PortId, ControllerIndex, Segment, Bus, Device, Function)
    return { PortId = PortId, ControllerIndex = ControllerIndex, Segment = Segment,
        Bus = Bus, Device = Device, Function = Function }
end

local function config_tbl_new(PortId, ControllerIndex, Segment, Bus, Device, Function)
    return { PortId or 0, ControllerIndex or 255, Segment or 0, Bus or 0, Device or 0, Function or 0 }
end

function c_bdf_config:build_bdf_cfgs()
    -- 初始化 configs
    local cfg
    if self.mds_obj.BDFConfigs and #self.mds_obj.BDFConfigs ~= 0 then
        for i, c in ipairs(self.mds_obj.BDFConfigs) do
            self.mds_obj.BDFConfigs[i] = config_tbl_new(table.unpack(c, 1, 6))
            ---@class BDFConfiguration @业务端口
            cfg = config_new(table.unpack(c, 1, 6))
            self.configs[i] = {
                socket_id = self.mds_obj.SocketId,
                type = cfg.Type,
                port_id = cfg.PortId,
                controller_index = cfg.ControllerIndex or 255,
                segment = cfg.Segment,
                bus = cfg.Bus,
                device = cfg.Device,
                func = cfg.Function
            }
        end
    end
end

function c_bdf_config:init()
    -- 将数组重新转成结构体
    if self.mds_obj.BDFConfigs and #self.mds_obj.BDFConfigs ~= 0 and
        #self.mds_obj.BDFConfigs[1] ~= 0 then
        for i, config in ipairs(self.mds_obj.BDFConfigs) do
            self.mds_obj.BDFConfigs[i] = config_tbl_new(table.unpack(config, 1, 6))
        end
    end
end

function c_bdf_config:ctor(mds_obj, position)
    self.mds_obj = mds_obj
    self.position = position
    self.configs = {}
end

return c_bdf_config
