-- 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: fructl的相关工具
local log = require 'mc.logging'
local class = require 'mc.class'
local mdb = require 'mc.mdb'
local context = require 'mc.context'
local skynet = require 'skynet'
local client = require 'network_adapter.client'

local FRUCTRL_ITF = 'bmc.kepler.Systems.FruCtrl'
local POWER_ON_LOCK_ITF = 'bmc.kepler.Systems.PowerOnLock'

local fructl = class()

function fructl.get_fructl_obj()
    local objects = client:GetFruCtrlObjects()
    local _, obj = next(objects)
    return obj
end

-- 获取上下电状态
function fructl.get_power_status()
    local obj = fructl.get_fructl_obj()
    if not obj then
        log:error('[network_adapter]get_power_status: get power object failed')
        return nil
    end
    return obj.PowerState
end

-- 获取复位状态
function fructl.get_system_reset_flag()
    local obj = fructl.get_fructl_obj()
    if not obj then
        log:error('[network_adapter]get_system_reset_flag: get power object failed')
        return nil
    end
    return obj.SysResetDetected
end

function fructl.get_mdb_sub_path_obj(bus, path, interface)
    local ok, obj_list = pcall(mdb.get_sub_objects, bus, path, interface)
    if not ok or next(obj_list) == nil then
        return nil
    end

    for _, obj in pairs(obj_list) do  -- 当前接口名唯一，故直接返回obj_list的第一个值
        return obj
    end
end

function fructl.set_power_on_lock(bus, system_id, state, timeout, reason, app_name)
    local path = '/bmc/kepler/Systems/' .. system_id .. '/FruCtrl'
    local interface = POWER_ON_LOCK_ITF
    local obj = fructl.get_mdb_sub_path_obj(bus, path, interface)
    if not obj then
        log:error('set_power_on_lock: get power object failed')
        return nil
    end
    return obj.pcall:SetPowerOnLock(context.new(), state, timeout, app_name, reason)
end

function fructl.set_poweron_lock_until_success(bus, sys_id, state, time, reason)
    local res
    local cnt = 0
    repeat
        res = fructl.set_power_on_lock(bus, sys_id, state, time, reason, 'network_adapter')
        if not res then
            skynet.sleep(50)
        end
        cnt = cnt + 1
    until res or cnt > 20
    if cnt > 20 and not res then
        log:notice('set power on lock failed, lock state : %s', state and 'lock' or 'unlock')
        return
    end
    log:notice('set power on lock success, lock state : %s', state and 'lock' or 'unlock')
end

return fructl