-- 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 singleton = require 'mc.singleton'
local class = require 'mc.class'
local skynet = require 'skynet'
local common_def = require 'common_def'

local ctrl_commu_loss_monitor = class()

local RAID_CONTROLLER_COMMUNICATION_LOSS_THRESHOLD<const> = 180

function ctrl_commu_loss_monitor:ctor()
    self.ctrl_last_fail_timestamp = {}
    self.mock_state = false
    self.ctrl_communication_loss_list = {}
end

function ctrl_commu_loss_monitor:update(frame_failed, ctrl_id)
    -- 当调用成功时清除计时
    if frame_failed == false then
        self.ctrl_last_fail_timestamp[ctrl_id] = 0
        self.ctrl_communication_loss_list[ctrl_id] = common_def.ctrl_commu_normal
        return
    end

    -- 当3分钟内一直调用不成功，报通信失败
    local cur_timestamp = skynet.time()
    local interval = 0
    if (not self.ctrl_last_fail_timestamp[ctrl_id]) or self.ctrl_last_fail_timestamp[ctrl_id] == 0 then
        self.ctrl_last_fail_timestamp[ctrl_id] = cur_timestamp
    end

    if cur_timestamp >= self.ctrl_last_fail_timestamp[ctrl_id] then
        interval = cur_timestamp - self.ctrl_last_fail_timestamp[ctrl_id]
    end

    if interval > RAID_CONTROLLER_COMMUNICATION_LOSS_THRESHOLD or self.mock_state == true then
        self.ctrl_communication_loss_list[ctrl_id] = common_def.ctrl_commu_loss
    else
        self.ctrl_communication_loss_list[ctrl_id] = common_def.ctrl_commu_normal
    end
end

function ctrl_commu_loss_monitor:get_ctrl_commu_loss(ctrl_id)
    return self.ctrl_communication_loss_list[ctrl_id]
end

function ctrl_commu_loss_monitor:mock_ctrl_commu_loss(state)
    self.mock_state = state
end

return singleton(ctrl_commu_loss_monitor)