-- 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 lu = require 'luaunit'
local ncsi_protocol_intf = require 'ncsi_protocol_intf'
local ncsi_utils = require 'ncsi.ncsi_protocol.ncsi_utils'
local ncsi_def = require 'ncsi.ncsi_protocol.ncsi_def'
local ncsi_parameter = require 'ncsi.ncsi_protocol.ncsi_parameter'

-- 测试套件
TestNCSIGetStatus = {}

-- 命令类型常量定义
local GET_LINK_STATUS_RSP = 0x8A
local GET_LINK_STATUS_RSP_LEN = 16
local LINK_ACCESS_ERROR = 6

-- 初始化全局NCSI参数
local mock_ncsi_parameter = {
    link_status = {},
    oem_link_status = {},
    iid = 1,  -- 添加iid字段，这是NCSI协议需要的包ID
    channel_cnt = 4,  -- 添加channel_cnt字段
    recv_buf = ''     -- 添加recv_buf字段
}

-- 初始化link_status和oem_link_status数组
for i = 1, 16 do
    mock_ncsi_parameter.link_status[i] = {}
    mock_ncsi_parameter.oem_link_status[i] = {}
    for j = 0, 3 do
        mock_ncsi_parameter.link_status[i][j] = {
            reserved3 = 0,
            tx_flow_control = 0,
            rx_flow_control = 0,
            link_partner8 = 0,
            serdes_link = 0,
            oem_link_speed = 0,
            reserved2 = 0,
            channel_available = 0,
            link_partner1 = 0,
            link_partner2 = 0,
            link_partner3 = 0,
            link_partner4 = 0,
            link_partner5 = 0,
            link_partner6 = 0,
            link_partner7 = 0,
            link_flag = 0,
            speed_duplex = 0,
            negotiate_flag = 0,
            negotiate_complete = 0,
            parallel_detection = 0
        }
        mock_ncsi_parameter.oem_link_status[i][j] = 0
    end
end

-- 重新加载ncsi_get_status模块以使用mock参数
package.loaded['ncsi.ncsi_protocol.ncsi_get_status'] = nil
local ncsi_get_status = require 'ncsi.ncsi_protocol.ncsi_get_status'

-- 模拟发送NCSI命令的函数
local function mock_send_ncsi_cmd(req_data, len, eth_name)
    TestNCSIGetStatus.last_req_data = req_data
    TestNCSIGetStatus.last_len = len
    TestNCSIGetStatus.last_eth_name = eth_name
    return 0
end

-- 初始化函数，在每个测试用例前执行
function TestNCSIGetStatus:setUp()
    ncsi_parameter.get_instance():init_ncsi_parameter()
    -- 保存原始函数
    self.original_send_ncsi_cmd = ncsi_protocol_intf.send_ncsi_cmd
    self.original_cmd_ctrl = ncsi_utils.ncsi_cmd_ctrl
    self.original_get_ncsi_parameter = ncsi_parameter.get_instance().get_ncsi_parameter

    -- 使用模拟函数替换原始函数
    ncsi_protocol_intf.send_ncsi_cmd = mock_send_ncsi_cmd

    -- 初始化测试变量
    self.last_req_data = nil
    self.last_len = nil
    self.last_eth_name = nil

    ncsi_parameter.get_instance().get_ncsi_parameter = function() 
        return mock_ncsi_parameter
    end

    -- 模拟cmd_ctrl函数以便测试
    ncsi_utils.ncsi_cmd_ctrl = function(_, _, req_packet, eth_name, cmd_process_table)
        -- 确保cmd_process_table存在
        assert(cmd_process_table, "cmd_process_table is nil")

        -- 调用请求处理函数
        if req_packet and req_packet.packet_head and req_packet.packet_head.packet_type and
           cmd_process_table[req_packet.packet_head.packet_type] then
            cmd_process_table[req_packet.packet_head.packet_type](req_packet, eth_name)
        end

        -- 返回成功
        return ncsi_def.NCSI_SUCCESS
    end
end

-- 清理函数，在每个测试用例后执行
function TestNCSIGetStatus:tearDown()
    -- 恢复原始函数
    ncsi_protocol_intf.send_ncsi_cmd = self.original_send_ncsi_cmd
    ncsi_utils.ncsi_cmd_ctrl = self.original_cmd_ctrl
    ncsi_parameter.get_instance().get_ncsi_parameter = self.original_get_ncsi_parameter
end

-- 测试获取链路状态功能
function TestNCSIGetStatus:test_get_link_status()
    -- 测试参数
    local package_id = 0
    local channel_id = 1
    local eth_name = "eth0"
    local eth_id = 1

    -- 执行测试
    local result = ncsi_get_status.ncsi_get_link_status(package_id, channel_id, eth_name, eth_id)

    -- 验证结果
    lu.assertEquals(result, ncsi_def.NCSI_SUCCESS)
    lu.assertNotNil(self.last_req_data)
    lu.assertEquals(self.last_eth_name, eth_name)

    -- 测试不同的package_id和channel_id组合
    self.last_req_data = nil
    result = ncsi_get_status.ncsi_get_link_status(1, 2, eth_name, eth_id)
    lu.assertEquals(result, ncsi_def.NCSI_SUCCESS)
    lu.assertNotNil(self.last_req_data)
end

-- 测试响应处理
function TestNCSIGetStatus:test_response_processing()
    -- 模拟响应包
    local function create_mock_response(rsp_code, reason_code, link_status, oem_link_status)
        local rsp = {packet_head = {}, payload = ''}
        rsp.packet_head.payload_len_hi = (GET_LINK_STATUS_RSP_LEN >> 8) & 0x0f
        rsp.packet_head.payload_len_lo = GET_LINK_STATUS_RSP_LEN & 0xff
        rsp.packet_head.packet_type = GET_LINK_STATUS_RSP
        rsp.packet_head.channel_id = 1

        -- 创建响应payload，按照bitstring结构组织数据
        local rsp_data = string.char(
            (rsp_code >> 8) & 0xFF, rsp_code & 0xFF,  -- rsp_code (2字节)
            (reason_code >> 8) & 0xFF, reason_code & 0xFF,  -- reason_code (2字节)
            0,  -- lnk_sts_reserved3 (8位)
            0,  -- lnk_sts_tx_flow_control (1位) 到 lnk_sts_parallel_detection (1位)
            0,  -- other_indication (32位)
            0, 0, 0, 0,
            0,  -- oem_link_status (32位)
            0, 0, 0, 0,
            0,  -- check_sum (32位)
            0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  -- pad_data (10字节)
            0, 0, 0, 0  -- fcs (4字节)
        )

        rsp.payload = rsp_data
        return rsp
    end

    -- 测试参数
    local package_id = 0
    local channel_id = 1
    local eth_name = "eth0"
    local eth_id = 1

    -- 测试成功响应
    local success_rsp = create_mock_response(ncsi_def.CMD_COMPLETED, 0, 0x1234, 0x5678)
    local original_cmd_ctrl = ncsi_utils.ncsi_cmd_ctrl

    ncsi_utils.ncsi_cmd_ctrl = function(_, _, req_packet, _, cmd_process_table)
        return cmd_process_table[GET_LINK_STATUS_RSP](success_rsp)
    end

    local result = ncsi_get_status.ncsi_get_link_status(package_id, channel_id, eth_name, eth_id)
    lu.assertEquals(result, ncsi_def.NCSI_SUCCESS)
    lu.assertNotNil(mock_ncsi_parameter.link_status[eth_id][channel_id])
    lu.assertNotNil(mock_ncsi_parameter.oem_link_status[eth_id][channel_id])

    -- 测试失败响应
    local fail_rsp = create_mock_response(0x0123, 1, 0, 0)
    
    ncsi_utils.ncsi_cmd_ctrl = function(_, _, req_packet, _, cmd_process_table)
        return cmd_process_table[GET_LINK_STATUS_RSP](fail_rsp)
    end

    result = ncsi_get_status.ncsi_get_link_status(package_id, channel_id, eth_name, eth_id)
    lu.assertEquals(result, ncsi_def.NCSI_FAIL)

    -- 测试硬件访问错误
    local hw_error_rsp = create_mock_response(0x0123, LINK_ACCESS_ERROR, 0, 0)
    
    ncsi_utils.ncsi_cmd_ctrl = function(_, _, req_packet, _, cmd_process_table)
        return cmd_process_table[GET_LINK_STATUS_RSP](hw_error_rsp)
    end

    result = ncsi_get_status.ncsi_get_link_status(package_id, channel_id, eth_name, eth_id)
    lu.assertEquals(result, ncsi_def.NCSI_FAIL)

    -- 恢复原始函数
    ncsi_utils.ncsi_cmd_ctrl = original_cmd_ctrl
end

-- 测试错误处理
function TestNCSIGetStatus:test_error_handling()
    -- 模拟cmd_ctrl返回失败
    local original_cmd_ctrl = ncsi_utils.ncsi_cmd_ctrl
    ncsi_utils.ncsi_cmd_ctrl = function(_, _, _, _, _)
        return ncsi_def.NCSI_FAIL
    end

    -- 测试参数
    local package_id = 0
    local channel_id = 1
    local eth_name = "eth0"
    local eth_id = 1

    -- 测试获取链路状态失败
    local result = ncsi_get_status.ncsi_get_link_status(package_id, channel_id, eth_name, eth_id)
    lu.assertEquals(result, ncsi_def.NCSI_FAIL)

    -- 恢复原始函数
    ncsi_utils.ncsi_cmd_ctrl = original_cmd_ctrl
end

-- 测试响应包为空的情况
function TestNCSIGetStatus:test_empty_response()
    -- 模拟响应包
    local function create_mock_response()
        local rsp = {packet_head = {}, payload = ''}
        rsp.packet_head.payload_len_hi = 0
        rsp.packet_head.payload_len_lo = 16

        local rsp_payload = '\0'
        rsp.payload = rsp_payload
        return rsp
    end
    -- 测试参数
    local package_id = 0
    local channel_id = 1
    local eth_name = "eth0"

    -- 模拟cmd_ctrl返回空响应
    local original_cmd_ctrl = ncsi_utils.ncsi_cmd_ctrl
    ncsi_utils.ncsi_cmd_ctrl = function(_, _, _, _, cmd_process_table)
        local empty_rsp = create_mock_response()
        return cmd_process_table[GET_LINK_STATUS_RSP](empty_rsp)
    end

    -- 测试获取状态
    local result = ncsi_get_status.ncsi_get_link_status(package_id, channel_id, eth_name, 1)
    lu.assertEquals(result, ncsi_def.NCSI_FAIL, "Should fail when response is nil")

    -- 恢复原始函数
    ncsi_utils.ncsi_cmd_ctrl = original_cmd_ctrl
end

return TestNCSIGetStatus