package org.springblade.system.log;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import tech.powerjob.worker.log.OmsLogger;

import java.util.LinkedList;

/**
 *  日志工具类
 * @author bfhuange
 * @date 2024/9/25
 */
@Slf4j
public class ComposeLogUtil {
    /**
     *  oms logger
     */
    private static final ThreadLocal<OmsLogger> OMS_LOGGER_CONTEXT = new ThreadLocal<>();
    /**
     *  组合 logger
     */
    private static final ThreadLocal<LinkedList<ComposeLogger>> CONTEXT = new ThreadLocal<>();
    /**
     *  默认日志记录器
     */
    private static final ComposeLogger DEFAULT = new ComposeLogger(log, null);
    private ComposeLogUtil() {}

    /**
     *  设置oms logger
     * @param omsLogger
     */
    public static void setOmsLogger(OmsLogger omsLogger) {
        OMS_LOGGER_CONTEXT.set(omsLogger);
    }

    /**
     *  获取oms logger
     * @return
     */
    public static OmsLogger getOmsLogger() {
        return OMS_LOGGER_CONTEXT.get();
    }

    /**
     *  移除oms logger
     */
    public static void removeOmsLogger() {
        OMS_LOGGER_CONTEXT.remove();
    }

    /**
     *  添加日志记录器
     * @param log
     */
    public static void addLog(Logger log) {
        LinkedList<ComposeLogger> list = CONTEXT.get();
        if (list == null) {
            list = new LinkedList<>();
            CONTEXT.set(list);
        }
        ComposeLogger omsLog = new ComposeLogger(log, ComposeLogUtil.getOmsLogger());
        list.addLast(omsLog);
    }

    /**
     *  获取最后一个日志记录器
     * @return
     */
    public static ComposeLogger getLastLog() {
        LinkedList<ComposeLogger> list = CONTEXT.get();
        if (list == null || list.isEmpty()) {
            return DEFAULT;
        }
        return list.getLast();
    }

    /**
     *  清除最后一个日志记录器
     */
    public static void removeLastLog() {
        LinkedList<ComposeLogger> list = CONTEXT.get();
        if (list == null || list.isEmpty()) {
            return;
        }
        list.removeLast();
    }
}
