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

local m = {}

function m.get_MemorysInfo(memorys_list)
    local list = cjson.json_object_new_array()
    local record
    for _, memory in ipairs(memorys_list) do
        record = cjson.json_object_new_object()
        record.SystemId = string.format('%d', memory.SystemId)
        record.TimeStamp = memory.TimeStamp
        record.TimeZone = memory.TimeZone
        record.Socket = memory.Socket
        record.Channel = memory.Channel
        record.Slot = memory.Slot
        record.DeviceLocator = memory.DeviceLocator
        record.SerialNumber = memory.SerialNumber
        record.HealthScore = memory.HealthScore
        record.IsolationStatus = memory.IsolationStatus
        list[#list + 1] = record
    end
    return list
end

function m.get_pending_mem_isolation(pending_list)
    local result = cjson.json_object_new_array()
    local isolation
    for index, item in ipairs(pending_list) do
        isolation = cjson.json_object_new_object()
        isolation.SystemId = string.format('%d', item.SystemId)
        isolation.SequenceNum = item.SequenceNum
        isolation.Time = utils.date_format(item.TimeStamp, "%Y-%m-%d %H:%M:%S", false)
        isolation.FailureMode = item.FailureMode
        isolation.AddressInfo = cjson.json_object_ordered_decode(item.AddressInfo)
        isolation.ExecutionStatus = item.ExecutionStatus
        result[index] = isolation
    end
    return result
end

local fpc_supported_list = {
    '/FPCService/Memory'
}

function m.get_fpc_members(license_status, managerid)
    local result = cjson.json_object_new_array()
    local member
    if license_status == true then
        for index, info in ipairs(fpc_supported_list) do
            member = cjson.json_object_new_object()
            member['@odata.id'] = '/redfish/v1/Managers/' .. managerid .. info
            result[index] = member
        end
    end
    return result
end

local PATTERN = "^(%a*)(%d+)$"
function m.get_system_id(system_id)
    if system_id == 'Enc' or system_id == 'Rack' then
        return 1
    end
    local _, sys_id = string.match(system_id, PATTERN)
    if tonumber(sys_id) == nil then
        error(base_messages.PropertyValueFormatError(system_id, 'SystemId'))
    end
    return tonumber(sys_id)
end

return m
