-- 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 log = require 'mc.logging'
local c_object_manage = require 'mc.orm.object_manage'
local port_comm = require 'device.class.nic_mgmt.port.port_comm'
local port_defs = require 'device.class.nic_mgmt.port.port_defs'
local port_manage = require 'device.class.nic_mgmt.port.port_manage'

local port_init = {}

local function init_id(orm_obj)
    local retry_times = 0

    -- bridge 不通过devicelocator生成ID信息
    if port_comm.is_virtual_port(orm_obj.Type) then
        return
    end
    local parent = orm_obj.parent
    while not parent or parent.NodeId == '' and retry_times < 10 do
        retry_times = retry_times + 1
        orm_obj.tasks:sleep_ms(1000)
    end
    orm_obj.NetworkAdapterId = parent.NodeId
    orm_obj.NodeId = parent.NodeId .. (orm_obj.PortID + 1)
end

function port_init.init(orm_obj, bus)
    log:notice('port orm obj init start, NetworkAdapterId is %s, PortId is %s',
        orm_obj.NetworkAdapterId, orm_obj.PortID)
    init_id(orm_obj)
    local parent = orm_obj.parent
    if parent and string.find(parent.NodeId, 'ROH') then
        return
    end
    orm_obj.t_port_prop_without_bma = {
        LinkStatus = port_defs.INVALID_DATA_STRING
    }
    if parent and parent.Model == port_defs.NPU_MODEL then
        log:notice('NPU%s port init start', parent.SlotNumber)
        port_manage.init_npu_port(orm_obj)
    else
        port_manage.register_property_changed_callback(orm_obj, bus)
        orm_obj.na_object_name, orm_obj.np_object_name = orm_obj.path:match('([^/]+)/Ports/([^/]+)')
        orm_obj.vlans = c_object_manage.get_instance().app:CreateVLANs(1, orm_obj.na_object_name,
            orm_obj.np_object_name,
                function(obj)
                obj.NetworkPortObjectName = orm_obj.na_object_name .. orm_obj.np_object_name
                local mdb_object = obj:get_mdb_object('bmc.kepler.Systems.NetworkPort.VLANs')
                rawset(mdb_object, 'get_parent', function()
                    return orm_obj
                end)
            end)
        orm_obj:next_tick(port_manage.update_mac_addr_from_db, orm_obj)
    end
    log:notice('port orm obj init success, NetworkAdapterId is %s, PortId is %s',
        orm_obj.NetworkAdapterId, orm_obj.PortID)
end

return port_init
