package cz.jzitnik.game.logic;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import cz.jzitnik.game.Game;
import cz.jzitnik.game.annotations.CustomLogic;
import cz.jzitnik.tui.ScreenRenderer;
import lombok.extern.slf4j.Slf4j;

import org.reflections.Reflections;

@Slf4j
public class CustomLogicProvider {
    private final List<CustomLogicInterface> logicList = new ArrayList<>();

    public void update(Game game, ScreenRenderer screenRenderer) {
        for (CustomLogicInterface logicInterface : logicList) {
            log.debug("Running logic {}.", logicInterface.getClass().getSimpleName());
            logicInterface.nextIteration(game, screenRenderer);
        }
    }

    public CustomLogicProvider() {
        log.info("Loading logic");
        registerHandlers();
    }

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

        for (Class<?> clazz : handlerClasses) {
            if (CustomLogicInterface.class.isAssignableFrom(clazz)) {
                try {
                    CustomLogicInterface instance = (CustomLogicInterface) clazz.getDeclaredConstructor().newInstance();
                    logicList.add(instance);
                    log.info("Loaded custom logic with name {}", clazz.getSimpleName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
