package net.querz.event;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Consumer;

public class EventManager {

	private EventTree events;
	private ExecutorService threadpool;

	public EventManager() {
		this(null);
	}

	public EventManager(ExecutorService threadpool) {
		events = new EventTree();
		if (threadpool == null) {
			this.threadpool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
			Runtime.getRuntime().addShutdownHook(new Thread(() -> this.threadpool.shutdownNow()));
		} else {
			this.threadpool = threadpool;
		}
	}

	public <T extends Event> EventFunction<T> registerEvent(Consumer<T> function, Class<T> eventClass) {
		return registerEvent(function, eventClass, 0);
	}

	public <T extends Event> EventFunction<T> registerEvent(Consumer<T> function, Class<T> eventClass, int priority) {
		return events.add(function, eventClass, priority);
	}

	public <T extends Event> void unregisterEvent(EventFunction<T> functionData) {
		events.remove(functionData);
	}


	public Future<Boolean> call(Event event) {
		if (event.isAsync()) {
			return threadpool.submit(new FutureEvent<>(event));
		} else {
			events.execute(event);
		}
		return null;
	}

	@Override
	public String toString() {
		return events.toString();
	}

	class FutureEvent<T extends Event> implements Callable<Boolean> {
		T event;

		FutureEvent(T event) {
			this.event = event;
		}

		@Override
		public Boolean call() throws Exception {
			events.execute(event);
			return event instanceof Cancellable && ((Cancellable) event).isCancelled();
		}
	}
}

@@ -268,16 +268,34 @@
 e events
+ = new EventTree()
 ;%0A%09priva
@@ -355,134 +355,8 @@
 ) %7B%0A
-%09%09this(null);%0A%09%7D%0A%0A%09public EventManager(ExecutorService threadpool) %7B%0A%09%09events = new EventTree();%0A%09%09if (threadpool == null) %7B%0A%09
 %09%09th
@@ -447,17 +447,16 @@
 s());%0A%09%09
-%09
 Runtime.
@@ -535,27 +535,70 @@
 w()));%0A%09
-%09%7D else
+%7D%0A%0A%09public EventManager(ExecutorService threadpool)
  %7B%0A
-%09
 %09%09this.t
@@ -621,20 +621,16 @@
 adpool;%0A
-%09%09%7D%0A
 %09%7D%0A%0A%09pub

simplify EventManaget constructor