package xtools.boot.thread.utils;

import lombok.extern.slf4j.Slf4j;
import xtools.boot.api.model.dto.log.HolderLogTrack;
import xtools.boot.api.model.dto.log.LogTrack;
import xtools.boot.log.LogBus;
import xtools.boot.log.enums.LogBusBaseType;
import xtools.boot.log.holder.LogTrackHolder;
import xtools.boot.thread.callback.VirtualThreadTaskCallback;
import xtools.core.enums.LogLevel;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>Title : VirtualThreadTaskUtils</p>
 * <p>Description : VirtualThreadTaskUtils</p>
 * <p>DevelopTools : Idea_x64_v2026.1</p>
 * <p>DevelopSystem : macOS Sequoia 15.7.5</p>
 * <p>Company : org.xujun</p>
 *
 * @author : XuJun
 * @version : 5.0.0
 * @date : 2026/2/8 20:46
 */
@Slf4j
public class VirtualThreadTaskUtils {

    /**
     * 创建子线程并执行任务(不带日志记录,不推荐)
     *
     * @param callback 回调
     */
    public static void simple(VirtualThreadTaskCallback callback) {
        ExecutorService service = Executors.newVirtualThreadPerTaskExecutor();
        try {
            // 创建子线程,并异步提交
            CompletableFuture.runAsync(() -> {
                try {
                    callback.callback();
                } catch (Exception e) {
                    log.error("子线程执行异常", e);
                }
            }, service);
        } finally {
            // 关闭线程池
            service.shutdown();
        }
    }

    /**
     * 创建子线程并执行任务(带日志记录,推荐)
     *
     * @param callback 回调
     */
    public static void execute(VirtualThreadTaskCallback callback) {
        // 获取父线程的追踪日志信息
        LogTrack logTrack = LogTrackHolder.get();
        LogBus.init(LogLevel.INFO, LogBusBaseType.VIRTUAL_THREAD, logTrack).title("创建虚拟线程").save();
        ExecutorService service = Executors.newVirtualThreadPerTaskExecutor();
        try {
            // 创建子线程,并异步提交
            CompletableFuture.runAsync(() -> {
                // 生成子线程的追踪日志信息
                HolderLogTrack holderLogTrack = LogTrackHolder.newThread(logTrack);
                ScopedValue.where(LogTrackHolder.getScoped(), holderLogTrack).run(() -> {
                    try {
                        callback.callback();
                    } catch (Exception e) {
                        LogBus.init(LogLevel.ERROR, LogBusBaseType.VIRTUAL_THREAD).error(e).title("子线程执行异常").save();
                    }
                });
            }, service);
        } finally {
            // 关闭线程池
            service.shutdown();
        }
    }


}
