-- Copyright (c) 2026 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 utils = require 'mc.utils'
local file_sec = require 'utils.file'
local utils_core = require 'utils.core'
local log = require 'mc.logging'
local cmn = require 'common'

local vrd_comm_method = {}

vrd_comm_method.DUMP_CHIP_TYPE = {
    MCU = 1,
    CPLD = 2
}

function vrd_comm_method:on_dump_vrd_cb(ctx, path, collection_table, chip_type)
    if chip_type == self.DUMP_CHIP_TYPE.MCU then
        -- 单独收集每个mcu的日志，并进行格式化处理，将处理好的结果存放在对应收集次数的数组中
        local mcu_id
        for _, mcu in pairs(collection_table) do
            mcu_id = mcu:get_id()
            mcu:get_vrd_dump_info(mcu_id)
        end
    end

    local print_data = ''
    for _, mcu in pairs(collection_table) do
        local file_data = mcu:get_vrd_log()
        if file_data then
            for _, v in pairs(file_data) do
                print_data = print_data .. v
            end
        end
    end
    local file_name = path .. '/vrd_reg_dump'
    local file, err = file_sec.open_s(file_name, 'w+')
    if not file then
        log:error('open %s failed, err: %s', file_name, err)
        return
    end
    utils.close(file, pcall(file.write, file, print_data))
    utils_core.chmod_s(file_name, utils.S_IRUSR | utils.S_IWUSR | utils.S_IRGRP)
    log:notice('vrd ifx info collect finish')
end

function vrd_comm_method:listen_vrd_abnormal(obj)
    local abnormal_flag = false
    local retries = 0
    local value
    local mcu_id = obj:get_id()
    while true do
        value = obj.interface:get_system_event()
        if not value or type(value) ~= 'number' then
            retries = retries + 1
        else
            retries = 0
            -- 第四位为基础板异常掉电事件，第五位为基础板上电超时事件，两事件互斥
            if value & 24 ~= 0 and not abnormal_flag then
                log:notice('[Vrd]vrd abnormal appear, start get dump')
                cmn.skynet.sleep(200) --硬件建议等待2s收集完成
                obj:get_vrd_dump_info(mcu_id)
                abnormal_flag = true
            -- 硬件确认故障后收集一次，直到故障消失
            elseif value & 24 == 0 and abnormal_flag then
                log:notice('[Vrd]vrd abnormal disappear, restart to listen')
                abnormal_flag = false
            end
        end
        if retries == 10 then
            -- 连续10次获取不到认为命令不通，停止轮询
            break
        end
        cmn.skynet.sleep(500) -- 每5s检测一次
    end
end

return vrd_comm_method