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.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.utils.UIUtils;

import java.util.List;

public class KeyboardFocusManager extends InputListener {
    private final List<Actor> focusOrder;

    public KeyboardFocusManager(Actor...focusOrder) {
        this.focusOrder = List.of(focusOrder);
    }

    @Override
    public boolean keyTyped(InputEvent event, char character) {
        var stage = event.getStage();
        if (character == '\t') {
            var currentFocus = stage.getKeyboardFocus();
            var index = currentFocus == null ? -1 : focusOrder.indexOf(currentFocus);
            var count = focusOrder.size();
            if (count == 0) return true;

            Actor nextFocus;
            if (index == -1) {
                nextFocus = focusOrder.get(UIUtils.shift() ? count - 1 : 0);
            } else {
                var direction = UIUtils.shift() ? -1 : 1;
                nextFocus = focusOrder.get(((index + direction) % count + count) % count);
            }

            if (nextFocus instanceof TextField textField) {
                textField.selectAll();
            }

            stage.setKeyboardFocus(nextFocus);
            event.stop();
            return true;
        } else {
            return false;
        }
    }
}
