package org.tio.sitexxx.service.service.jpush.huawei.messaging;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2025-02-21 10:23
 *    desc   :
 * </pre>
 */
public class HuaweiScheduledExecutor extends ScheduledThreadPoolExecutor {

    public HuaweiScheduledExecutor(ThreadFactory threadFactory, String name) {
        this(threadFactory, name, null);
    }

    public HuaweiScheduledExecutor(ThreadFactory threadFactory, String name, Thread.UncaughtExceptionHandler handler) {
        super(1, decorateThreadFactory(threadFactory, name, handler));
        setRemoveOnCancelPolicy(true);
    }

    static ThreadFactory getThreadFactoryWithName(ThreadFactory threadFactory, String name) {
        return decorateThreadFactory(threadFactory, name, null);
    }

    private static ThreadFactory decorateThreadFactory(
            ThreadFactory threadFactory, String name, Thread.UncaughtExceptionHandler handler) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(name));
        ThreadFactoryBuilder builder = new ThreadFactoryBuilder()
                .setThreadFactory(threadFactory)
                .setNameFormat(name)
                .setDaemon(true);
        if (handler != null) {
            builder.setUncaughtExceptionHandler(handler);
        }
        return builder.build();
    }
}
