-- 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_file = require 'utils.file'
local utils_core = require 'utils.core'
local log = require 'mc.logging'
local cjson = require 'cjson'

local m = {}

local function get_file_content(path)
    if not utils_core.is_file(path) then
        log:info('File not exist')
        return
    end

    local file = utils_file.open_s(path, 'r')
    if not file then
        log:error('Open file failed')
        return
    end
    local data = file:read('*a')
    file:close()

    return data
end

function m.get_file_json(path)
    local content = get_file_content(path)
    if not content then
        error(base_messages.InternalError())
    end
    return cjson.json_object_ordered_decode(content)
end

function m.get_message_json(path)
    local src = m.get_file_json(path)
    local obj = cjson.json_object_new_object()
    for k, v in pairs(src.Messages or {}) do
        local one = cjson.json_object_new_object()
        one.Description = v.Description
        one.Message = v.Message
        one.Severity = v.Severity
        one.NumberOfArgs = v.NumberOfArgs
        one.ParamTypes = v.ParamTypes
        one.Resolution = v.Resolution
        obj[k] = one
    end
    return obj
end

return m