-- Copyright (c) 2026 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 class = require 'mc.class'
local org_freedesktop_dbus = require 'sd_bus.org_freedesktop_dbus'
local log = require 'mc.logging'
local signal = require 'mc.signal'

local SYSTEM_PATH <const> = '/bmc/kepler/Systems/'
local FRU_PATH <const> = '/FruCtrl'

local c_bus_monitor_service = class()

function c_bus_monitor_service:ctor(bus)
    self.bus = bus
    self.bus_monitors = {}
    self.on_os_state_changed = signal.new()
end

function c_bus_monitor_service:fru_monitor()
    -- 监视FRU状态
    local fru_path = string.format('%s%d%s', SYSTEM_PATH, 1, FRU_PATH)
    local fru_bus_sig = org_freedesktop_dbus.MatchRule.signal('PropertiesChanged'):with_interface(
        org_freedesktop_dbus.SD_BUS_PROPERTIES):with_path_namespace(fru_path)

    -- 注册响应函数
    local fru_slot = self.bus:match(fru_bus_sig, function(msg)
        local _, values = msg:read('sa{sv}as')
        if values.PowerState then
            if values.PowerState:value() == 'OFF' then
                self.on_os_state_changed:emit(false)
            elseif values.PowerState:value() == 'ON' then
                self.on_os_state_changed:emit(true)
            end
        end
    end)

    self.bus_monitors['PowerState'] = fru_slot
end

function c_bus_monitor_service:init()
    self:fru_monitor()
end

return singleton(c_bus_monitor_service)