package cz.jzitnik.events.handlers;

import cz.jzitnik.annotations.EventHandler;
import cz.jzitnik.annotations.injectors.InjectDependency;
import cz.jzitnik.annotations.injectors.InjectState;
import cz.jzitnik.events.MouseAction;
import cz.jzitnik.events.MouseMoveEvent;
import cz.jzitnik.game.GameState;
import cz.jzitnik.game.objects.GameObject;
import cz.jzitnik.game.objects.Interactable;
import cz.jzitnik.utils.DependencyManager;
import cz.jzitnik.utils.UIClickHandlerRepository;
import cz.jzitnik.utils.events.AbstractEventHandler;
import cz.jzitnik.utils.events.EventManager;

import java.util.Optional;

@EventHandler(MouseAction.class)
public class MouseActionEventHandler extends AbstractEventHandler<MouseAction> {
    public MouseActionEventHandler(DependencyManager dm) {
        super(dm);
    }

    @InjectDependency
    private EventManager eventManager;

    @InjectDependency
    private UIClickHandlerRepository uiClickHandlerRepository;

    @InjectState
    private GameState gameState;

    @Override
    public void handle(MouseAction event) {
        if (gameState.getScreen() != null) {
            gameState.getScreen().handleMouseAction(event);
            return;
        }

        switch (event.getActionType()) {
            case MOVE -> eventManager.emitEvent(new MouseMoveEvent(event));
            case CLICK_RELEASE -> {
                Optional<GameObject> object = gameState.getCurrentRoom().getObjects().stream().filter(GameObject::isSelected).findFirst();

                if (object.isPresent()) {
                    ((Interactable) object.get()).interact(dm);
                    return;
                }

                uiClickHandlerRepository.handleClick(event);
            }
        }
    }
}
