-- 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.

-- Description: sel event process.
local log = require 'mc.logging'
local cc = require 'sel.sel_const'
local utils = require 'sensor_utils'
local json = require 'cjson'

local sel_event = {}
sel_event.__index = sel_event

function sel_event.new(db)
    return setmetatable({
        addr = cc.EVENT_RECEIVER_DISABLE,
        lun = 0,
        db = db,
        recovered_sel_msgs = {}
    }, sel_event)
end

function sel_event:initialize()
    local records = self.db:query_all_sel_msgs()
    if not records then
        log:notice('there is no sel msgs in t_sel_msg_list')
        return
    end

    -- 以sensor_id为索引，提高恢复传感器信息的效率
    local msg, sensor_id
    for _, record in pairs(records) do
        msg = record.__datas
        sensor_id = msg.SensorId
        if not self.recovered_sel_msgs[sensor_id] then
            self.recovered_sel_msgs[sensor_id] = {}
        end
        table.insert(self.recovered_sel_msgs[sensor_id], msg)
    end
end

function sel_event:get_recovered_sel_msgs(sensor_id)
    return self.recovered_sel_msgs[sensor_id]
end

function sel_event:set_event_receiver(addr, lun)
    self.addr = addr
    self.lun = lun
end

function sel_event:get_event_receiver()
    return self.addr, self.lun
end

function sel_event:add_sel_msg(msg)
    if not self.db:insert_sel_msg(msg) then
        return false
    end
    log:info('sel list add: %s', json.encode(msg))
    return true
end

-- 支持两种方式删除sel记录
-- 1. 根据index删除指定sel记录
-- 2. 根据sel信息匹配后删除该sel记录
function sel_event:remove_sel_msg(mode, data)
    if mode == utils.SEL_INDEX_MODE then
        local record = self.db:get_sel_msg(data)
        if not record then
            log:error('msg of index[%d] is not existed', data)
            return false
        end
        self.db:delete_sel_msg(record)
        return true
    end

    local records = self.db:query_sel_msg(mode, data)
    if not records then
        log:info('sel msg is not existed: %s', json.encode(data))
        return false
    end
    for _, record in pairs(records) do
        self.db:delete_sel_msg(record)
    end
    return true
end

function sel_event:find_sel_msg(mode, msg)
    if mode == utils.SEL_NO_CONDITION then
        return self.db:query_all_sel_msgs()
    end
    return self.db:query_sel_msg(mode, msg)
end


return sel_event