package cz.jzitnik.game.handlers.tooluse;

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

import cz.jzitnik.game.Game;
import cz.jzitnik.game.annotations.ToolUse;
import cz.jzitnik.game.entities.items.ItemType;

import org.reflections.Reflections;

public class ToolUseProvider {
    public final HashMap<ItemType, ToolUseHandler> handler = new HashMap<>();

    public ToolUseProvider() {
        registerHandlers();
    }

    public boolean handle(ItemType itemType, Game game, int x, int y) {
        if (!handler.containsKey(itemType)) {
            return false;
        }

        handler.get(itemType).handle(game, x, y);

        return true;
    }

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

        for (Class<?> clazz : handlerClasses) {
            if (ToolUseHandler.class.isAssignableFrom(clazz)) {
                try {
                    ToolUseHandler handlerInstance = (ToolUseHandler) clazz.getDeclaredConstructor()
                            .newInstance();
                    ToolUse annotation = clazz.getAnnotation(ToolUse.class);
                    ItemType key = annotation.value();
                    handler.put(key, handlerInstance);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
