-- 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.

-- Description: retimer对象管理
local singleton = require 'mc.singleton'
local log = require 'mc.logging'
local retimer_upgrade_service = require 'retimer.upgrade.retimer_upg_service'
local retimer_map = {
    [0] = require 'retimer.retimer',
    [3] = require 'retimer.retimer_M88RT51632'
}

local retimer_service = {}
retimer_service.__index = retimer_service

function retimer_service:on_add_object(class_name, object, position)
    local switch = {
        ['Retimer'] = function ()
            local retimer_class = retimer_map[object.ChipType]
            if retimer_class then
                local obj = retimer_class.new(object, self.bus)
                obj:register_firmware_info()
                self.retimer_collection[object.name] = obj
                log:notice('add object, class: %s, name: %s, position: %s', class_name, object.name, position)
            end
        end
    }

    if switch[class_name] then
        switch[class_name]()
    end
end

function retimer_service:on_delete_object(class_name, object, position)
    local reimter_obj = self.retimer_collection[object.name]
    if not reimter_obj then
        return
    end
    reimter_obj:cleanup()
    self.retimer_collection[object.name] = nil
    log:notice('delete object, class: %s, name: %s, position: %s', class_name, object.name, position)
end

function retimer_service.new()
    return setmetatable({retimer_collection = {}}, retimer_service)
end

function retimer_service:init(bus)
    self.bus = bus
    self.retimer_upgrade_service = retimer_upgrade_service.new()
    self.retimer_upgrade_service:init(bus, self.retimer_collection)
end

return singleton(retimer_service)
