-- Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
-- 
-- this file licensed under the 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 client = require 'thermal_mgmt.client'
local log = require 'mc.logging'

local fructl_data = class()

function fructl_data:ctor(bus)
    self.bus = bus
    self.path = '/bmc/kepler/Systems/1/FruCtrl'
    self.intf = 'bmc.kepler.Systems.FruCtrl'
    self.power_state = "ON"
end

function fructl_data:init()
    self.slot = self:fructl_listenning()
end

-- 防止模块重启监听电源状态获取不到值
function fructl_data:get_all_infos()
    local power_state -- 临时属性 判断电源状态是否获取成功
    client:ForeachFruCtrlObjects(function (obj)
        if obj.PowerState and string.len(obj.PowerState) > 0 then
            power_state = obj.PowerState
            self.power_state = obj.PowerState
            log:notice('Current PowerState is %s', self.power_state)
        end
    end)
    if not power_state then -- 获取FruCtrl对象失败
        log:error('Get FruCtrl obj(interface:%s) failed', self.intf)
    end
end

function fructl_data:update_all_datas()
    self:get_all_infos()
end
-- FruCtrl监听
function fructl_data:fructl_listenning()
    return client:OnFruCtrlPropertiesChanged(function(prop_value, path, interface)
        self:fructl_changed_handle(interface, prop_value)
    end)
end

-- 监听回调函数
function fructl_data:fructl_changed_handle(interface, dics)
    if interface ~= self.intf or not dics["PowerState"] then
        return
    end

    self.power_state = dics["PowerState"]:value()

    log:notice("PowerState changed to %s", tostring(self.power_state))
end

return fructl_data