package de.renew.simulatorontology.serialisation;


import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Manages the {@link SerialisationListener} instances.
 */
public final class SerialisationListenerRegistry {
    private static final Map<Class<?>, SerialisationListener<?>> LISTENERS = new HashMap<>();

    /**
     * Adds a new listener for the given type. If a listener is already set, nothing happens.
     *
     * @param type the class of the objects the listeners listens for
     * @param listener the new listener
     */
    public static <T> void addListener(Class<T> type, SerialisationListener<T> listener) {
        LISTENERS.putIfAbsent(type, listener);
    }

    /**
     * Returns the configured listener for the given class.
     *
     * @param type the class of the objects the listeners listens for
     * @return the configured listener
     */
    @SuppressWarnings("unchecked")
    public static <T> Optional<SerialisationListener<T>> getListener(Class<T> type) {
        return Optional.ofNullable((SerialisationListener<T>) LISTENERS.get(type));
    }
}
