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

local m = {}

-- 事件的格式变为kv类型的结构体数组
local function format_sel_list(sel_list)
    -- 计算结构体参数个数
    local num = 0
    local end_flag = sel_list[1].MappingTable[1].Key
    for key, value in pairs(sel_list) do
        if value.MappingTable[1].Key == end_flag and key ~= 1 then
            break
        end
        num = num + 1
    end
    -- 格式化结构体,num个结构体构成一条Sel
    local count = 0
    local res = {}
    local sel = {}
    for _, v in pairs(sel_list) do
        sel[v.MappingTable[1].Key] = v.MappingTable[1].Value
        count = count + 1
        if count % num == 0 then
            res[#res + 1] = sel
            sel = {}
        end
    end
    return res
end

function m.get_reversed_index_count(total, skip, top)
    local count = top
    local index = total - skip - count + 1
    if index <= 0 then
        count = count + index - 1
        index = 1
    end
    count = count < 0 and 0 or count
    return {
        Index = index,
        Count = count
    }
end

function m.get_result(total, sel_list)
    if not sel_list or #sel_list == 0 then
        return {
            TotalCount = 0,
            List = {}
        }
    end
    local res = format_sel_list(sel_list)
    local results = {}
    local sel_item
    for i = 1, #res, 1 do
        sel_item = res[i]
        results[#results + 1] = {
            ID = sel_item.RecordId,
            Timestamp = mc_utils.date_format(tonumber(sel_item.Timestamp), '%Y-%m-%d %H:%M:%S', false),
            Level = sel_item.Level,
            SensorName = sel_item.SensorName,
            SensorType = sel_item.SensorType,
            Status = sel_item.Status,
            Description = sel_item.Description,
        }
    end
    return {
        TotalCount = total,
        List = results
    }
end

return m
