-- 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 class = require 'mc.class'
local log = require 'mc.logging'
local skynet = require 'skynet'
local c_bmc_start_flag = class()

local START_FINISH = 1
local flag = false

function c_bmc_start_flag:ctor()

end

function c_bmc_start_flag:add_bmcstartflag_callback(object)
    self.obj = object
end

function c_bmc_start_flag:get_bmc_start_flag()
    if self.obj == nil then
        log:error('c_bmc_start_flag object dose not exist')
        return nil
    end
    local ok, start_flag = pcall(function()
        return self.obj['Value']
    end)

    if not ok or not start_flag then
        log:info('[BMC FruCtrl]cannot get BMC startup completed flag from CPLD')
        return nil
    end
    log:info('[BMC FruCtrl]get BMC startup completed flag %s', start_flag)
    return start_flag
end

function c_bmc_start_flag:update_bmc_start_flag()
    if flag then
        return
    end
    flag = true
    skynet.fork_once(function()
        local start_flag = self:get_bmc_start_flag()
        if start_flag == nil or start_flag == START_FINISH then
            log:notice('[BMC FruCtrl] start_flag is %s', start_flag)
            return
        end

        local ok
        while true do
            ok = pcall(function()
                -- 需要通过硬件访问代理服务设置BMC启动的标志给天池组件BCU的CPLD, 因此使用pcall处理
                self.obj['Value'] = START_FINISH
            end)

            if ok then
                -- 再读一次确认设置是否生效
                start_flag = self:get_bmc_start_flag()
                if start_flag == START_FINISH then
                    log:notice("[BMC FruCtrl]set BMC startup completed flag to CPLD successfully")
                    return
                end
            end

            skynet.sleep(2000)
        end
    end)
end

return c_bmc_start_flag