-- 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 singleton = require 'mc.singleton'
local log = require 'mc.logging'
local led_service = require 'led_service'
local client = require 'chassis.client'
local custom_tool = require 'common_tools.custom_tool'

local LED_POLICY_INTF<const> = 'bmc.kepler.Systems.Led.Policy'
local EVENTS_PATH<const> = '/bmc/kepler/Systems/1/Events'
local SENSORS_PATH<const> = '/bmc/kepler/Chassis/1/Sensors'

local led_policy_service = {}
led_policy_service.__index = led_policy_service

function led_policy_service.new()
    return setmetatable({
        led_policy_obj = nil, -- 亮灯策略对象
    }, led_policy_service)
end

function led_policy_service:get_health()
    local events_objs = client:GetEventsObjects()[EVENTS_PATH]
    if events_objs == nil then
        log:error('Get events objs failed')
        return nil
    end
    local health = events_objs.Health
    if health == nil then
        log:error('Get health failed')
        return nil
    end
    log:notice('Chassis_led_policy get_health:%s', health)
    return health
end

function led_policy_service:get_sel_health()
    local sensors_objs = client:GetSensorsObjects()[SENSORS_PATH]
    if sensors_objs == nil then
        log:error('Get sensors objs failed')
        return nil
    end
    local health = sensors_objs.Health
    if health == nil then
        log:error('Get sel health failed')
        return nil
    end
    log:notice('Chassis_led_policy get_sel_health:%s', health)
    return health
end

function led_policy_service:add_object(object)
    self.led_policy_obj = object
    -- 注册亮灯策略属性变化回调
    local obj = object:get_mdb_object(LED_POLICY_INTF)
    obj.property_changed:on(function(name, value, sender)
        local customer = custom_tool.get_customer()
        log:notice('Chassis_led_policy get_customer:%s', customer)
        local health = customer ~= 'ByteDance' and self:get_health() or self:get_sel_health()
        if health ~= nil then
            led_service.get_instance():set_led_by_sys_health(health)
        end
    end)
end

return singleton(led_policy_service)
