-- 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 class = require 'mc.class'
local log = require 'mc.logging'
local initiator = require 'mc.initiator'
local singleton = require 'mc.singleton'

local utils = class(require 'mc.utils')

local LOG_LEVEL<const> = {
    ERROR = 1,
    INFO = 2,
    DEBUG = 3,
    NOTICE = 4
}

function utils:ctor()
    self.global_property = {}
    self.last_time_map = {}
end

function utils.operation_log(ctx, fmt, ...)
    local intf = (ctx and ctx.Interface) and ctx.Interface or 'N/A'
    local user_name = (ctx and ctx.UserName) and ctx.UserName or 'N/A'
    local client_addr = (ctx and ctx.ClientAddr)  and ctx.ClientAddr or '127.0.0.1'
    log:operation(initiator.new(intf, user_name, client_addr), 'power_mgmt', fmt, ...)
end

-- 限频日志
---@param level number params: 1,error 2,info 3,debug
---@param interval_s number params: interval seconds
function utils:frequency_limit_log(level, interval_s, fmt, ...)
    local last_time_key = debug.getinfo(2, 'S').short_src .. ':' .. debug.getinfo(2, "l").currentline
    local cur_time = os.time()
    local log_callback = {
        [LOG_LEVEL.ERROR] = log.error,
        [LOG_LEVEL.INFO] = log.info,
        [LOG_LEVEL.DEBUG] = log.debug,
        [LOG_LEVEL.NOTICE] = log.notice
    }

    local last_time = self.last_time_map[last_time_key]
    if not last_time or cur_time - last_time >= interval_s then
        self.last_time_map[last_time_key] = cur_time
        log_callback[level](log, fmt, ...)
    end
end

return singleton(utils)