-- 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 bs_util = require 'util.base_util'
local json = require "cjson"
local log = require 'mc.logging'
local prop_def = require 'macros.property_def'

local E_OK<const> = 1
local E_FAILED<const> = -1

local json_util = {}

function json_util.json_to_list(json_data, traverse_list)
    if not json_data or not traverse_list then
        return nil
    end

    local list = {}
    local index = 1
    local len = #traverse_list
    for i = 1, len , 1 do
        local key = traverse_list[i]
        local val = json_data[key]
        if val then
            list[index] = key
            index = index + 1
        end
    end

    return list
end

function json_util.get_list(json_data)
    if not json_data then
        return nil
    end

    local list = {}
    local index = 1
    for k, _ in pairs(json_data) do
        list[index] = k
        index = index + 1
    end

    return list
end

function json_util.write_file_extend(file_path, user_json_data, is_append)
    local file_json_data = user_json_data
    if is_append then
        local current_file_json_data = bs_util.get_file_order_json(file_path)
        if current_file_json_data then
            for k, v in pairs(user_json_data) do
                current_file_json_data[k] = nil
                current_file_json_data[k] = v
            end
            file_json_data = current_file_json_data
        end
    end

    local ok, ret = pcall(function()
        return json.json_object_dump_pretty(file_json_data, file_path)
    end)

    -- 返回值1表示成功
    if ok and ret and ret == 1 then
        return E_OK
    end

    log:error('write_file_extend json_object_dump_pretty failed, ret = %s', ret)
    return E_FAILED
end

function json_util.write_file_data(file_json_data, file_path)
    local ok, ret = pcall(function()
        return json.json_object_dump_pretty(file_json_data, file_path)
    end)

    -- 返回值1表示成功
    if ok and ret == 1 then
        return prop_def.E_OK
    end

    log:error('write_file_extend json_object_dump_pretty failed, ret = %s', ret)
    return prop_def.E_FAILURE
end


return json_util