-- 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 skynet = require 'skynet'
local log = require 'mc.logging'
local m_enums = require 'types.enums'

local M = {}

M.power_ctrl_state_enums = {
    INITED = 0,
    PROCESSING = 1,
    INTERRUPTED = 2,
}

function M.wait_chassis_power_off(power_cycle_ins, power_off_timeout)
    while power_off_timeout > 0 do
        -- 当前不支持中断powercycle操作
        if power_cycle_ins.power_ctrl_state == M.power_ctrl_state_enums.INTERRUPTED then
            log:notice("[chassis power cycle] power cycle interrupted in power offing")
            return false
        end
        -- 循环检测系统电源信号，等待系统下电
        if power_cycle_ins.chassis_fructrl_obj.PowerState == m_enums.PowerStatus.OFF then
            log:notice("[chassis power cycle] power cycle finished from power cycle")
            break
        end

        skynet.sleep(100) -- 延时1000ms
        power_off_timeout = power_off_timeout - 1
    end
    -- 超时还未成功下电，记录日志
    if power_off_timeout == 0 then
        log:error("[chassis power cycle] power-off failed in the poweroff scenario")
        return false
    end

    log:notice("[chassis power cycle] Power off time is %d when do power cycle", 1200 - power_off_timeout)
    return true
end

return M