-- 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 signal = require 'mc.signal'

local signal_mgr = class()

-- 创建信号
local function signal_new()
    local sig = {
        signal = signal.new(),
        ok = false,
        signal_cache = {}
    }

    -- 监听信号触发点
    function sig:listen(p1, p2, p3)
        -- 如果就绪，直接执行响应
        if self.ok then
            self.signal:emit(p1, p2, p3)
            return
        end
        -- 如果未就绪，将响应存到cache中等待触发
        self.signal_cache[#self.signal_cache + 1] = function()
            self.signal:emit(p1, p2, p3)
        end
    end

    -- 注册信号触发后的响应
    function sig:on(cb)
        self.signal:on(cb)
    end

    -- 释放，状态置为OK，执行所有存在cache中的响应
    function sig:emit()
        self.ok = true
        -- 执行所有存在cache中的响应
        local signal_cache = self.signal_cache
        self.signal_cache = {}
        for _, s in ipairs(signal_cache) do
            s()
        end
    end

    -- 状态置为 NOT OK，响应将会被存到cache中
    function sig:cache()
        self.ok = false
    end

    return sig
end

-- 注册信号
function signal_mgr:register(name)
    self.signals[name] = signal_new()
    return self.signals[name]
end

function signal_mgr:get(name)
    return self.signals[name]
end

function signal_mgr:ctor()
    self.signals = {}
end

return singleton(signal_mgr)