package cz.jzitnik.game.handlers.pickup;

import java.util.HashMap;
import java.util.Set;

import cz.jzitnik.game.annotations.PickupHandler;
import org.reflections.Reflections;

public class PickupHandlerProvider {
    public final HashMap<String, CustomPickupHandler> pickupList = new HashMap<>();

    public CustomPickupHandler get(String itemId) {
        return pickupList.get(itemId);
    }

    public PickupHandlerProvider() {
        registerHandlers();
    }

    private void registerHandlers() {
        Reflections reflections = new Reflections("cz.jzitnik.game.handlers.pickup.handlers");
        Set<Class<?>> handlerClasses = reflections.getTypesAnnotatedWith(PickupHandler.class);

        for (Class<?> clazz : handlerClasses) {
            if (CustomPickupHandler.class.isAssignableFrom(clazz)) {
                try {
                    CustomPickupHandler handlerInstance = (CustomPickupHandler) clazz.getDeclaredConstructor()
                            .newInstance();
                    PickupHandler annotation = clazz.getAnnotation(PickupHandler.class);
                    String key = annotation.value();
                    if (!key.contains(",")) {
                        pickupList.put(key, handlerInstance);
                    } else {
                        String[] keys = key.split(",");
                        for (String keyx : keys) {
                            pickupList.put(keyx, handlerInstance);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
