-- 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 base_messages = require 'messages.base'
local log = require 'mc.logging'
local json = require 'cjson'

local export_import_engine = class()

local CONFIG_DATA = "ConfigData"

local function get_config(config_string)
    local ok, config_json = pcall(function()
        return json.decode(config_string)
    end)
    if not ok or config_json == nil then
        log:error("[power_mgmt]import power_mgmt json: json format error")
        error(base_messages.MalformedJSON())
    end
    return config_json[CONFIG_DATA]
end

-- 配置导入
function export_import_engine.import(ctx, config_string)
    local config = get_config(config_string)
    if config == nil then
        log:notice('[power_mgmt] import power_mgmt josn: no need import')
        return
    end

    pcall(function()
        local customize_config = require 'customize_cfg'
        return customize_config.config_import_data(config)
    end)
end

-- 配置导出
function export_import_engine.export(ctx)
    local config = {}
    local ok, _ = pcall(function()
        local customize_config = require 'customize_cfg'
        return customize_config.config_export_data(config)
    end)
    if not ok then
        log:error("[power_mgmt]export power_mgmt config: export power_mgmt fail")
        error(base_messages.InternalError())
    end
    local user_config_data
    ok, user_config_data = pcall(function()
        return json.encode(config)
    end)
    if not ok then
        log:error("[power_mgmt]export power_mgmt config: encode config fail")
        error(base_messages.InternalError())
    end
    return user_config_data
end

return export_import_engine