package me.proxylink.plugin.tunnel;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

final class NamedThreadFactory implements ThreadFactory {
    private final String prefix;
    private final boolean virtual;
    private final AtomicInteger nextId = new AtomicInteger(1);

    NamedThreadFactory(String prefix) {
        this(prefix, false);
    }

    NamedThreadFactory(String prefix, boolean virtual) {
        this.prefix = prefix;
        this.virtual = virtual;
    }

    @Override
    public Thread newThread(Runnable runnable) {
        if (virtual) {
            return Thread.ofVirtual()
                    .name(prefix + "-", nextId.getAndIncrement())
                    .unstarted(runnable);
        }
        Thread thread = new Thread(runnable, prefix + "-" + nextId.getAndIncrement());
        thread.setDaemon(false);
        return thread;
    }
}
