-- 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 m = {}
local cjson = require 'cjson'
local mc_ctx = require 'mc.context'

function m.get_expand_parameters(is_clear_conf)
    local ret_paras = {}

    if is_clear_conf then
        ret_paras.RestoreFactorySettings = 'true'
    end

    return ret_paras
end

function m.get_upgrade_progress(progress)
    local res = cjson.json_object_new_array()
    local UPDATE_SERVICE = "bmc.kepler.firmware_mgmt"
    local UPDATE_SERVICE_PATH = "/bmc/kepler/UpdateService"
    local UPDATE_SERVICE_INF = "bmc.kepler.UpdateService"
    local _, progress_tbl = bus:call(UPDATE_SERVICE, UPDATE_SERVICE_PATH, UPDATE_SERVICE_INF,
        'GetUpdateProgress', 'a{ss}', (mc_ctx.get_context() or mc_ctx.new()))
    local object
    for _, value in pairs(progress_tbl) do
        object = cjson.json_object_new_object()
        -- 升级任务名
        object['TaskName'] = value.TaskName or value[1]
        -- 升级固件描述
        object['Component'] = value.Firmware or value[2]
        -- 升级包名称
        object['FileName'] = value.FileName or value[4]
        -- 升级进度
        object['Percentage'] = value.Percentage or value[5]
        -- 升级状态
        object['TaskState'] = value.TaskState or value[6]
        -- 升级任务错误码
        object['ErrorCode'] = tonumber(value.ErrorCode or value[7])
        -- 固件预计升级的剩余时间
        object['EstimatedRemainingTime'] = value.EstimatedRemainingTime and tonumber(value.EstimatedRemainingTime)
        res[#res + 1] = object
    end
    return res
end

function m.get_pending_list(list)
    local res = cjson.json_object_new_array()
    local object
    for _, value in pairs(list) do
        object = cjson.json_object_new_object()
        object['SystemId'] = value.SystemId
        object['FirmwareType'] = value.Firmware
        object['ActiveStatus'] = value.ActiveStatus
        object['ActiveAction'] = value.ActiveAction
        res[#res + 1] = object
    end
    return res
end

function m.get_packages(path)
    local res = {}
    local package = {path, {}}
    res[#res + 1] = package
    return res
end

function m.get_active_policy(policy)
    if not policy or #policy == 0 then
        return {}
    end
    local res
    -- 如果有重复值也当作一个值处理
    -- 同时传入两个策略则直接取值ResetAC
    for _, value in pairs(policy) do
        if not res then
            res = value
        elseif res ~= policy then
            res = 'ResetAC'
            break
        end
    end

    return {ActivationControl = res}
end

return m
