package com.ghost.technic.server.game.event;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

public class EventBus {

    private final Map<EventType, List<EventListener>> listeners = new EnumMap<>(EventType.class);

    public void subscribe(EventType type, EventListener listener) {
        listeners.computeIfAbsent(type, k -> new ArrayList<>()).add(listener);
    }

    public void unsubscribe(EventType type, EventListener listener) {
        if (listeners.containsKey(type)) {
            listeners.get(type).remove(listener);
        }
    }

    public void publish(GameEvent event) {
        List<EventListener> eventListeners = listeners.get(event.getType());
        if (eventListeners != null) {
            for (EventListener listener : new ArrayList<>(eventListeners)) {
                listener.handle(event);
            }
        }
    }
}
