-- 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 utils = require 'mc.utils'

local m = {}

function m.validate_and_get_prams(req_body)
    local ret_table = utils.string_split(req_body, ',', true)
    if not ret_table then error(base_messages.InternalError()) end
    -- 生效模式：1表示升级后需要手动重启BMC；2表示升级后自动重启BMC。默认值为2
    if ret_table[2] ~= nil and ret_table[2] ~= '1' and ret_table[2] ~= '2' then
        error(base_messages.InternalError())
    end
    local expand_param = {}
    expand_param.ActiveMode = ret_table[2] == '1' and 'ResetBMC' or 'Immediately'
    return {ret_table[1], expand_param}
end

-- V2 snmp升级状态错误值
local UPGRADE_NOT_PERFORM <const> = -1
local UPGRADE_FILE_LOADING <const> = -2
local UPGRADE_CHECK_PREUPGRADE <const> = -3
local UPGRADE_FILE_NOT_EXIST <const> = -4
local UPGRADE_FILE_UPLOAD_FAILED <const> = -5
local UPGRADE_OUTOF_MEMORY <const> = -6
local UPGRADE_INVALID_UPGADEPACKAGE <const> = -7
local UPGRADE_NOT_SUPPORT_INCURRENT_STATE <const> = -8
local UPGRADE_UPGRADE_FAILED <const> = -9
local UPGRADE_UPGRADE_MISMATCH_FILE <const> = -10
local UPGRADE_UPGRADE_FIRMWARE_WRONG_ME_STATUS <const> = -11
local UPGRADE_UPGRADE_UNKNOWN_ERR <const> = -12
local UPGRADE_WHITEBRAND_MISMATCH_FILE <const> = -13
local UPGRADE_POWERING_ON_ERR <const> = -14
local UPGRADE_FIRMWARE_VERSION_EARLY_ERR <const> = -15
local COPROCESSOR_FIRMWARE_UPGRADE_FAILED <const> = -16
-- 错误引擎到snmp错误值的映射
local error2snmp_map = {
    FileNotExist = UPGRADE_FILE_NOT_EXIST,
    InvalidFirmwarePackage = UPGRADE_INVALID_UPGADEPACKAGE,
    FirmwareFileMismatch = UPGRADE_UPGRADE_MISMATCH_FILE,
    FirmwarePackageVersionTooEarly = UPGRADE_FIRMWARE_VERSION_EARLY_ERR
}
local COPROCESSOR_ERROR_ARGS = "coprocessor firmware upgrade failed"
function m.get_upgrade_state(state, process, message_id, message_args)
    if state == 'Exception' then
        if message_args[1] and message_args[1] == COPROCESSOR_ERROR_ARGS then
            return COPROCESSOR_FIRMWARE_UPGRADE_FAILED
        end
        return error2snmp_map[message_id] or UPGRADE_UPGRADE_FAILED
    end

    return process
end

return m
