-- 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 switch_c = require 'domain.device.switch.switch'
local log = require 'mc.logging'
local monitor = require 'domain.debug.monitor'
local defs = require 'domain.defs'
local mgt = class()

function mgt:ctor(db)
    self.switch_collection = {}
    self.complete_positions = {}
    self.db = db
end

function mgt:get_switch(id)
    if self.switch_collection[id] then
        return self.switch_collection[id]
    end
    self.switch_collection[id] = switch_c.new(self.db, id)
    return self.switch_collection[id]
end

function mgt:on_add_object(class_name, object, position)
    local switch = {
        ['LswSwitchInfo'] = function()
            local switch = self:get_switch(object.Unit)
            switch:add_object(object)
            if not self.complete_positions[position] then
                self.complete_positions[position] = {}
            end
            table.insert(self.complete_positions[position], object.Unit)
        end,
        ['LswPhyInfo'] = function()
            local switch = self:get_switch(object.Unit)
            switch:add_phy(object)
        end,
        ['LswPortInfo'] = function()
            local switch = self:get_switch(object.Unit)
            switch:add_port(object)
        end,
        ['LswVlanInfo'] = function()
            local switch = self:get_switch(object.Unit)
            switch:add_vlan(object)
        end
    }

    if switch[class_name] then
        switch[class_name]()
        log:debug('[app_lsw] Add object, Class: %s, Position:%s', class_name, position)
    end
end

function mgt:on_add_object_complete(position)
    local mtr = monitor.get_instance()
    mtr:update_state(defs.NetConfigIdx.OnAddObject, true)

    local units = self.complete_positions[position]
    if not units then
        return
    end
    for _, v in pairs(units) do
        self.switch_collection[v]:start_init()
    end
end

return mgt