-- 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 singleton = require 'mc.singleton'
local log = require 'mc.logging'
local method_misc = require 'method_misc'
local class = require 'mc.class'

local config_manager = class()

function config_manager:add_nvme_config_obj_cb(object, position)
    object.position = position
    table.insert(self.nvme_configs, object)
end

function config_manager:del_nvme_config_obj_cb(object, position)
    method_misc:remove_ele_by_position(self.nvme_configs, position)
end


function config_manager:on_add_object(class_name, object, position)
    local switch = {
        ['NVMeConfig'] = function ()
            self:add_nvme_config_obj_cb(object, position)
        end
    }

    if switch[class_name] then
        switch[class_name]()
        log:notice('[ConfigManager] Add object, class: %s, position: %s', class_name, position)
    end
end

function config_manager:on_delete_object(class_name, object, position)
    local switch = {
        ['NVMeConfig'] = function ()
            self:del_nvme_config_obj_cb(object, position)
        end
    }

    if switch[class_name] then
        switch[class_name]()
        log:notice('[ConfigManager] Delete object, class: %s, position: %s', class_name, position)
    end
end

function config_manager:init(bus, db)
    self.nvme_configs = {}
    log:info('[ConfigManager] init finished.')
end

-- 根据背板UID和硬盘槽位号匹配对应的SystemId
function config_manager:get_nvme_systemid(uid, slot_id)
    if not uid then
        return
    end
    local match_config
    -- MultiHostMappings:[1]--UID,[2]--SlotId,[3]--SystemdId
    for _, v in pairs(self.nvme_configs) do
        for _, config in pairs(v.MultiHostMappings) do
            if uid == config[1] then
                match_config = config
            end
        end
    end
    if not match_config then
        return
    end
    for idx, slot in pairs(match_config[2]) do
        if slot == slot_id then
            return match_config[3][idx]
        end
    end
end

return singleton(config_manager)