-- 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 singleton = require 'mc.singleton'
local log = require 'mc.logging'
local ub_port_obj = require 'unit_manager.class.unit.ubinterface.ubport_obj'
local cmn = require 'common'

local ubport_service = class()

function ubport_service:on_add_object(class_name, object, position)
    local ubport_obj = ub_port_obj.new(object, position)
    table.insert(self.ubport_obj_table, ubport_obj)
    log:notice('[UBPort] Add object, class: %s, position: %s', class_name, position)
    self:register_listen_linkstatus_change(object)
end

function ubport_service:on_delete_object(class_name, object, position)
    cmn.remove_ele_by_position(self.ubport_obj_table, position)
    log:notice('[UBPort] Delete object, class: %s, position: %s', class_name, position)
end

function ubport_service:register_listen_linkstatus_change(obj)
    local switch = {
        [0] = 'linkdown',
        [1] = 'linkup',
        [255] = 'nolink'
    }
    obj.property_changed:on(function (name, value)
        if name == 'LinkStatusFromSMC' then
            if switch[value] then
                obj.LinkStatus = switch[value]
            end
        end
    end)
end

function ubport_service:ctor()
    self.ubport_obj_table = {}
end

return singleton(ubport_service)