-- 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 singleton = require 'mc.singleton'
local card_comm = require 'device.class.network_card_adapter.card_comm'
local card_device_asset_data = require 'device.class.network_card_adapter.device_tree.card_device_asset_data'

local card_device_tree = {}
card_device_tree.__index = card_device_tree

function card_device_tree.new()
    return setmetatable({}, card_device_tree)
end

local function get_card_device_tree_obj()
    local card_device_tree_obj = nil
    return card_device_tree_obj
end

local function properties_synchronizer(device_obj, resource_obj)
    card_comm.update_root_bdf(device_obj, resource_obj)
    card_comm.update_associated_resource(device_obj, resource_obj)

    device_obj:listen('DeviceName', function(_, value)
        if not card_comm.param_validator(value) then
            return
        end
        card_comm.set_resource_id_and_node_id(device_obj.Type, device_obj.DeviceName,
            device_obj.Location, resource_obj)
    end)

    card_comm.listen_update_resource_tree_property(device_obj, resource_obj)
end

function card_device_tree:init_asset_data_info(resource_obj)
    if not resource_obj then
        log:error("resource_obj is nil")
        return
    end
    card_device_asset_data.init_asset_data(resource_obj)
end

function card_device_tree:init_id(resource_obj)
    -- bridge 不通过devicelocator生成ID信息
    local device_obj = get_card_device_tree_obj()
    if not device_obj or resource_obj then
        log:error("device_obj or resource_obj is nil")
        return
    end
    if card_comm.is_virtual_port(device_obj.Type) then
        return
    end
    resource_obj.BoardIDHex = string.format('0x%04x', device_obj.Id)

    local retry_times = 0
    while not card_comm.param_validator(device_obj.DeviceName) and retry_times < 10 do
        retry_times = retry_times + 1
        resource_obj.tasks:sleep_ms(5000)
    end
    card_comm.set_resource_id_and_node_id(device_obj.Type, device_obj.DeviceName,
        device_obj.Location, resource_obj)

    resource_obj:register_mdb_objects()
    properties_synchronizer(device_obj, resource_obj)
end

return singleton(card_device_tree)