package com.yd.csf.service.utils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.Supplier;

/**
 * CompletableFuture兼容性工具类
 * 提供Java 8兼容的CompletableFuture方法
 */
public class CompletableFutureUtil {

    /**
     * Java 8兼容的failedFuture方法
     * 替代Java 9+的CompletableFuture.failedFuture()
     */
    public static <T> CompletableFuture<T> failedFuture(Throwable ex) {
        CompletableFuture<T> future = new CompletableFuture<>();
        future.completeExceptionally(ex);
        return future;
    }

    /**
     * 创建已完成的异常Future（别名方法）
     */
    public static <T> CompletableFuture<T> completedExceptionally(Throwable ex) {
        return failedFuture(ex);
    }

    /**
     * 安全的join方法，避免CompletionException包装
     * 直接抛出原始异常
     */
    public static <T> T safeJoin(CompletableFuture<T> future) {
        try {
            return future.join();
        } catch (CompletionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            } else if (cause instanceof Error) {
                throw (Error) cause;
            } else {
                throw new RuntimeException(cause);
            }
        }
    }

    /**
     * 带超时的supplyAsync方法（Java 8兼容）
     */
    public static <T> CompletableFuture<T> supplyAsyncWithTimeout(Supplier<T> supplier, long timeout, java.util.concurrent.TimeUnit unit) {
        CompletableFuture<T> future = CompletableFuture.supplyAsync(supplier);

        // 使用定时器模拟超时
        java.util.Timer timeoutTimer = new java.util.Timer();
        timeoutTimer.schedule(new java.util.TimerTask() {
            @Override
            public void run() {
                if (!future.isDone()) {
                    future.completeExceptionally(new java.util.concurrent.TimeoutException("Operation timed out after " + timeout + " " + unit.name().toLowerCase()));
                }
            }
        }, unit.toMillis(timeout));

        return future.whenComplete((result, throwable) -> timeoutTimer.cancel());
    }

    /**
     * 批量等待所有Future完成
     */
    @SafeVarargs
    public static CompletableFuture<Void> allOf(CompletableFuture<?>... futures) {
        return CompletableFuture.allOf(futures);
    }

    /**
     * 批量等待任意Future完成
     */
    @SafeVarargs
    public static <T> CompletableFuture<T> anyOf(CompletableFuture<T>... futures) {
        return CompletableFuture.anyOf(futures).thenApply(obj -> (T) obj);
    }

    /**
     * 延迟执行的CompletableFuture
     */
    public static <T> CompletableFuture<T> delayedFuture(long delay, java.util.concurrent.TimeUnit unit, Supplier<T> supplier) {
        CompletableFuture<T> future = new CompletableFuture<>();

        java.util.Timer timer = new java.util.Timer();
        timer.schedule(new java.util.TimerTask() {
            @Override
            public void run() {
                try {
                    T result = supplier.get();
                    future.complete(result);
                } catch (Exception e) {
                    future.completeExceptionally(e);
                } finally {
                    timer.cancel();
                }
            }
        }, unit.toMillis(delay));

        return future;
    }
}