-- Copyright (c) 2025 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 SEVERITY_MAP = {
    ['0'] = "OK",
    ['1'] = "Warning",
    ['2'] = "Warning",
    ['3'] = "Critical",
}

local function get_value_by_key(sel_list, key)
    if not sel_list then
        return
    end
    for _, v in pairs(sel_list) do
        if v.MappingTable[1].Key == key then
            return v.MappingTable[1].Value
        end
    end
end

function m.get_members(count, skip, top)
    if not count then
        return
    end
    skip = skip or 0
    top = top or (count > 32 and 32 or count)
    if count <= tonumber(skip) then
        return
    end
    local list = {}
    for i = 1, top, 1 do
        if (count - skip - i + 1) > 0 then
            list[i] = string.format('/redfish/v1/Managers/1/LogServices/SEL/Entries/%s', count - skip - i + 1)
        end
    end
    return list
end


function m.is_valid_entries_id(sel_total, entries_id)
    local id_num = tonumber(entries_id)
    return id_num and id_num <= sel_total
end

function m.get_record_seq(sel_list, entries_id)
    if not sel_list then
        return
    end
    local record = tonumber(entries_id) - 1
    for _, v in pairs(sel_list) do
        if v.MappingTable[1].Key == 'RecordSeq' then
            local value = tonumber(v.MappingTable[1].Value)
            if value then
                record = record + value
            end
            break
        end
    end
    return record
end

function m.get_time(sel_list)
    return get_value_by_key(sel_list, 'Timestamp')
end

function m.get_code(sel_list)
    return get_value_by_key(sel_list, 'EventCode')
end

function m.get_generator(sel_list)
    return get_value_by_key(sel_list, 'GenerateId')
end

function m.get_desc(sel_list)
    return get_value_by_key(sel_list, 'Description')
end

function m.get_sensor_number(sel_list)
    return tonumber(get_value_by_key(sel_list, 'SensorNumber'))
end

function m.get_sensor_type(sel_list)
    return get_value_by_key(sel_list, 'SensorType')
end

function m.get_severity(sel_list)
    local level = get_value_by_key(sel_list, 'Level')
    return level and SEVERITY_MAP[level]
end

return m