package cz.jzitnik.utils.events;

import cz.jzitnik.annotations.Dependency;
import cz.jzitnik.annotations.EventHandler;
import cz.jzitnik.annotations.injectors.InjectConfig;
import cz.jzitnik.annotations.injectors.InjectState;
import cz.jzitnik.config.EventThreadPoolConfig;
import cz.jzitnik.states.RunningState;
import cz.jzitnik.utils.DependencyManager;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.w3c.dom.events.EventException;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.concurrent.*;

@Slf4j
@Dependency
public class EventManager extends Thread {
    @InjectState
    private RunningState runningState;
    @InjectConfig
    private EventThreadPoolConfig eventThreadPoolConfig;

    private ExecutorService eventExecutor;
    private final HashMap<Class<? extends Event>, AbstractEventHandler<? extends Event>> handlers = new HashMap<>();
    private final BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<>();
    private final DependencyManager dependencyManager;

    @SuppressWarnings("unchecked")
    private <T extends Event> AbstractEventHandler<T> getHandler(Class<T> type) {
        return (AbstractEventHandler<T>) handlers.get(type);
    }

    public void emitEvent(Event event) {
        eventQueue.add(event);
    }

    @SuppressWarnings("unchecked")
    public EventManager(Reflections reflections, DependencyManager dependencyManager) {
        this.dependencyManager = dependencyManager;
        setDaemon(true);

        var classes = reflections.getTypesAnnotatedWith(EventHandler.class);

        for (var clazz : classes) {
            EventHandler eventHandler = clazz.getAnnotation(EventHandler.class);
            try {
                var instance = (AbstractEventHandler<? extends Event>) clazz.getDeclaredConstructor(DependencyManager.class).newInstance(dependencyManager);
                handlers.put(eventHandler.value(), instance);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                     NoSuchMethodException e) {
                log.error("Failed to instantiate event handler: {}", clazz.getName(), e);
            }
        }
    }

    @Override
    public void run() {
        for (Object instance : handlers.values()) {
            dependencyManager.inject(instance);
        }

        eventExecutor = Executors.newFixedThreadPool(eventThreadPoolConfig.getThreadCount());
        while (runningState.isRunning()) {
            try {
                Event event = eventQueue.take();
                handleEvent(event);
            } catch (InterruptedException e) {
                // The game is shutting down.
                eventExecutor.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
        eventExecutor.shutdown();
    }

    @SuppressWarnings("unchecked")
    private <T extends Event> void handleEvent(Event event) {
        T typedEvent = (T) event;
        AbstractEventHandler<T> handler = getHandler((Class<T>) event.getClass());

        if (handler != null) {
            eventExecutor.submit(() -> {
                try {
                    handler.handle(typedEvent);
                } catch (Exception e) {
                    log.error("Error", e);
                }
            });
        }
    }
}
