/*
 * This file is part of LuckPerms, licensed under the MIT License.
 *
 *  Copyright (c) lucko (Luck) <luck@lucko.me>
 *  Copyright (c) contributors
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 */

package me.lucko.luckperms.common.plugin.scheduler;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Abstract implementation of {@link SchedulerAdapter} using a {@link ScheduledExecutorService}.
 */
public abstract class AbstractJavaScheduler implements SchedulerAdapter {
    private final ScheduledExecutorService asyncExecutor = new AsyncExecutor();

    @Override
    public Executor async() {
        return this.asyncExecutor;
    }

    @Override
    public SchedulerTask asyncLater(Runnable task, long delay, TimeUnit unit) {
        ScheduledFuture<?> future = this.asyncExecutor.schedule(new WrappedRunnable(task), delay, unit);
        return () -> future.cancel(false);
    }

    @Override
    public SchedulerTask asyncRepeating(Runnable task, long interval, TimeUnit unit) {
        ScheduledFuture<?> future = this.asyncExecutor.scheduleAtFixedRate(new WrappedRunnable(task), interval, interval, unit);
        return () -> future.cancel(false);
    }

    @Override
    public void shutdown() {
        this.asyncExecutor.shutdown();
        try {
            this.asyncExecutor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static final class WrappedRunnable implements Runnable {
        private final Runnable delegate;

        WrappedRunnable(Runnable delegate) {
            this.delegate = delegate;
        }

        @Override
        public void run() {
            try {
                this.delegate.run();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static final class AsyncExecutor extends ScheduledThreadPoolExecutor {
        AsyncExecutor() {
            super(4, new ThreadFactoryBuilder().setNameFormat("luckperms-%d").build());
        }

        @Override
        public void execute(Runnable command) {
            super.execute(new WrappedRunnable(command));
        }
    }
}

@@ -1367,37 +1367,181 @@
 ort 
-java.util.concurrent.Executor
+org.checkerframework.checker.nullness.qual.NonNull;%0A%0Aimport java.util.concurrent.Executor;%0Aimport java.util.concurrent.ExecutorService;%0Aimport java.util.concurrent.Executors
 ;%0Aim
@@ -1641,65 +1641,8 @@
 re;%0A
-import java.util.concurrent.ScheduledThreadPoolExecutor;%0A
 impo
@@ -1902,42 +1902,441 @@
 ice 
-asyncExecutor = new AsyncExecutor(
+scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()%0A            .setDaemon(true)%0A            .setNameFormat(%22luckperms-scheduler%22)%0A            .build()%0A    );%0A%0A    private final ErrorReportingExecutor workerPool = new ErrorReportingExecutor(Executors.newCachedThreadPool(new ThreadFactoryBuilder()%0A            .setDaemon(true)%0A            .setNameFormat(%22luckperms-worker-%25d%22)%0A            .build()%0A    )
 );%0A%0A
@@ -2399,29 +2399,26 @@
 rn this.
-asyncExecutor
+workerPool
 ;%0A    %7D%0A
@@ -2557,49 +2557,55 @@
 his.
-asyncExecutor.schedule(new WrappedRunnabl
+scheduler.schedule(() -%3E this.workerPool.execut
 e(ta
@@ -2815,28 +2815,24 @@
  = this.
-asyncExecuto
+schedule
 r.schedu
@@ -2845,34 +2845,44 @@
 xedRate(
-new WrappedRunnabl
+() -%3E this.workerPool.execut
 e(task),
@@ -3015,29 +3015,70 @@
    this.
-asyncExecutor
+scheduler.shutdown();%0A        this.workerPool.delegate
 .shutdow
@@ -3117,21 +3117,27 @@
 his.
-asyncExecutor
+workerPool.delegate
 .awa
@@ -3296,31 +3296,38 @@
 l class 
-WrappedRunnable
+ErrorReportingExecutor
  impleme
@@ -3330,24 +3330,24 @@
 lements 
-Runnable
+Executor
  %7B%0A     
@@ -3363,23 +3363,30 @@
 e final 
-Runnabl
+ExecutorServic
 e delega
@@ -3402,31 +3402,53 @@
     
-WrappedRunnable(Runnabl
+private ErrorReportingExecutor(ExecutorServic
 e de
@@ -3548,37 +3548,45 @@
 oid 
-run() %7B%0A            try %7B%0A   
+execute(@NonNull Runnable command) %7B%0A
     
@@ -3585,33 +3585,32 @@
 ) %7B%0A            
- 
 this.delegate.ru
@@ -3611,101 +3611,53 @@
 ate.
-run();%0A            %7D catch (Exception e) %7B%0A                e.printStackTrace();%0A            %7D
+execute(new ErrorReportingRunnable(command));
 %0A   
@@ -3705,307 +3705,391 @@
 ass 
-AsyncExecutor extends ScheduledThreadPoolExecutor %7B%0A        AsyncExecutor() %7B%0A            super(4, new ThreadFactoryBuilder().setNameFormat(%22luckperms-%25d%22).build());%0A        %7D%0A%0A        @Override%0A        public void execute(Runnable command) %7B%0A            super.execute(new WrappedRunnable(command));
+ErrorReportingRunnable implements Runnable %7B%0A        private final Runnable delegate;%0A%0A        private ErrorReportingRunnable(Runnable delegate) %7B%0A            this.delegate = delegate;%0A        %7D%0A%0A        @Override%0A        public void run() %7B%0A            try %7B%0A                this.delegate.run();%0A            %7D catch (Exception e) %7B%0A                e.printStackTrace();%0A            %7D
 %0A   

Refactor AbstractJavaScheduler to make use of a cached thread pool