-- 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 skynet = require 'skynet'
local log = require 'mc.logging'
local mdb = require 'mc.mdb'
local ctx = require 'mc.context'

local comp_intf = 'bmc.kepler.Systems.Component'
require 'event.json_types.Events'
local test_sn = {}

-- 格式化查询的事件，便于直接通过Key拿到属性
local function format_event_list(list)
    if #list == 0 then
        return {}
    end
    -- 计算结构体参数个数num，接口返回的list为 sel * num 个数组,无法通过key直接获取sel对象，同时一个对象的参数个数不固定
    local num = 0
    local end_flag = list[1].MappingTable[1].Key -- 以第一个Key为标记，重复时说明遍历到第二个对象
    for key, value in pairs(list) do
        if value.MappingTable[1].Key == end_flag and key ~= 1 then
            break
        end
        num = num + 1
    end
    local count = 0
    local res = {}
    local event = {}
    for _, v in pairs(list) do
        event[v.MappingTable[1].Key] = v.MappingTable[1].Value
        count = count + 1
        if count % num == 0 then -- 每num个参数组成一个对象
            local temp = event
            event = {}
            res[#res + 1] = temp
        end
    end
    return res
end


function test_sn:test_sn(bus)
    -- 模拟初次插入，校验初始SN 预期'Stub'
    local hdd_comp = mdb.get_object(bus, '/bmc/kepler/Systems/1/Components/Component_HddBackplane_1_0105', comp_intf)
    assert(hdd_comp['SerialNumber'] == 'Stub', 'actual: ' .. hdd_comp['SerialNumber'])
    assert(hdd_comp['SerialNumber'] == hdd_comp['PreviousSN'], 'actual: ' .. hdd_comp['PreviousSN'])
    -- 模拟更新
    local stub_comp = mdb.get_object(bus, '/bmc/kepler/Systems/1/Components/Component_Stub_0105', comp_intf)
    stub_comp.Name = '123'
    skynet.sleep(50)
    assert(hdd_comp['SerialNumber'] == '123', 'actual: ' .. hdd_comp['SerialNumber'])
    assert(hdd_comp['PreviousSN'] == 'Stub', 'actual: ' .. hdd_comp['PreviousSN'])
    -- 模拟更新NA，预期不变
    stub_comp.Name = 'N/A'
    assert(hdd_comp['SerialNumber'] == '123', 'actual: ' .. hdd_comp['SerialNumber'])
    assert(hdd_comp['PreviousSN'] == 'Stub', 'actual: ' .. hdd_comp['PreviousSN'])
    -- 查询事件记录有替换事件
    local events_obj = mdb.get_object(bus, '/bmc/kepler/Systems/1/Events', 'bmc.kepler.Systems.Events')
    local _, rsp = events_obj:GetEventList_PACKED(ctx.new(), 1, 10, {}):unpack()
    rsp = format_event_list(rsp)
    assert(rsp[1].EventCode == '0x02000023', 'actual: ' .. rsp[1].EventCode)
end



return test_sn