-- 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: 高温下电检测

local log = require 'mc.logging'
local class = require 'mc.class'
local utils = require 'types.utils'

local c_therm_trip = class()

function c_therm_trip:ctor(object, id)
    self.obj = object
    self.system_id = id
    self.therm_flag = false -- 两个cpu使用同一个全局变量，其中一个高温均会下电
    self.therm_trip_callbacks = {}
    log:notice_easy("[System:%s]set therm_trip object successfully, uptime: %s.", id, utils.uptime())
end

function c_therm_trip:init()
    -- 私有属性属性变更监听
    self.obj.property_changed:on(function(name, value)
        if name == 'GetThermTrip' or name == 'GetThermTrip2' then
            self:therm_trip_check(value)
        end
    end)
end

function c_therm_trip:register_therm_trip_callback(cb)
    table.insert(self.therm_trip_callbacks, cb)
end

function c_therm_trip:execute_therm_trip_callbadk()
    for _, cb in pairs(self.therm_trip_callbacks) do
        cb()
    end
end

function c_therm_trip:therm_trip_check(val)
    if val == 0 then
        return
    end
    if self.therm_flag then
        log:notice_easy('[System:%s]Already in therm trip...', self.system_id)
        return
    end
    self.therm_flag = true

    self:execute_therm_trip_callbadk()

    -- 清除标记
    log:notice_easy('[System:%s]Clear therm trip.', self.system_id)
    self:clear_therm_trip()
    self.therm_flag = false
end

function c_therm_trip:get_thermtrip_actions()
    return self.obj.Actions
end

function c_therm_trip:get_thermtrip_seconds()
    return self.obj.TimeDelaySeconds
end

function c_therm_trip:clear_therm_trip()
    log:notice_easy('[System:%s]Start to clear therm trip......', self.system_id)
    local ok, err = pcall(function ()
        self.obj.SetThermTrip = 0
        self.obj.SetThermTrip2 = 0
    end)
    if not ok then
        log:error('[System:%s]clear therm trip failed, err:%s',self.system_id, err)
    end
end

return c_therm_trip