-- 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 _, skynet = pcall(require, 'skynet')
local retimer_upgrade_service = require 'retimer.upgrade.retimer_upg_service'
local retimer_map = {
    [0] = require 'retimer.retimer',
    [6] = require 'retimer.retimer_M88RT51632',
    [7] = require 'retimer.retimer_CS81532'
}

local retimer_service = {}
retimer_service.__index = retimer_service

function retimer_service:on_add_object(class_name, object, position)
    local switch = {
        ['Retimer'] = function ()
            -- 防止轮询时间过长，采用协程执行
            skynet.fork_once(function()
                local retry_cnt = 0
                -- ChipType从scanner获取。需要通过轮询确保从寄存器中获取到值。255是对该scanner未分发时设置的默认值
                while retry_cnt < 300 and object.ChipType == 255 do
                    skynet.sleep(100)
                    retry_cnt = retry_cnt + 1
                end

                local retimer_class = retimer_map[object.ChipType]
                if retimer_class then
                    local obj = retimer_class.new(object, self.bus, position)
                    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)
                    return
                end
                log:error("Failed to obtain %s ChipType: %s", object.name, object.ChipType)
            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)
