-- 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 context = require('mc.context')
local MDB_SERVICE <const> = 'bmc.kepler.power_mgmt'
local MDB_INTERFACE <const> = 'bmc.kepler.Systems.PowerMgmt.OnePower'

local SET_PSU_SWITCH_SUCCESS <const> = 0
local PSU_NOT_PRESENT <const> = 1
local NOT_SUPPORT_PSU_SWITCH <const> = 2
local INVALID_PSU_STATUS <const> = 3
local SET_PSU_SWITCH_FAILED <const> = 4

local m = {}

function m.set_psu_switch(path, reset_type)
    if not path or type(path) ~= 'string' or #path == 0 then
        return PSU_NOT_PRESENT
    end

    local reset_type_name = 'Unknown'
    if reset_type == 2 then
        reset_type_name = 'ForceRestart'
    end

    local err, _ = bus:pcall(
        MDB_SERVICE,
        path,
        MDB_INTERFACE,
        'Reset',
        'a{ss}s',
        context.get_context() or context.new(),
        reset_type_name
    )
    if err then
        if err.name == 'ActionNotSupported' then
            return NOT_SUPPORT_PSU_SWITCH
        elseif err.name == 'ResetOperationNotAllowed' then
            return INVALID_PSU_STATUS
        else
            return SET_PSU_SWITCH_FAILED
        end
    end
    return SET_PSU_SWITCH_SUCCESS
end

return m