package eu.jonahbauer.wizard.client.libgdx.listeners;

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;

public class AutoFocusListener extends InputListener {
    @Override
    public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
        var target = event.getTarget();

        while (target != null && !(target instanceof ScrollPane)) {
            target = target.getParent();
        }

        if (target instanceof ScrollPane pane) {
            event.getStage().setScrollFocus(pane);
        } else {
            event.getStage().setScrollFocus(null);
        }
    }

    @Override
    public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
        var target = event.getTarget();

        while (target != null && !(target instanceof ScrollPane)) {
            target = target.getParent();
        }

        if (target == null || toActor == null || !toActor.isDescendantOf(target)) {
            event.getStage().setScrollFocus(null);
        }
    }
}
