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

import com.badlogic.gdx.Input;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox;

public class SelectBoxListener extends InputListener {
    private final SelectBox<?> selectBox;

    public SelectBoxListener(SelectBox<?> selectBox) {
        this.selectBox = selectBox;
    }

    @Override
    public boolean keyDown(InputEvent event, int keycode) {
        var size = selectBox.getItems().size;
        if (size == 0) return false;

        switch (keycode) {
            case Input.Keys.UP -> {
                var index = selectBox.getSelectedIndex();
                if (index == -1) {
                    selectBox.setSelectedIndex(size - 1);
                } else {
                    selectBox.setSelectedIndex(MathUtils.clamp(index - 1, 0, size - 1));
                }
                return true;
            }
            case Input.Keys.DOWN -> {
                var index = selectBox.getSelectedIndex();
                if (index == -1) {
                    selectBox.setSelectedIndex(0);
                } else {
                    selectBox.setSelectedIndex(MathUtils.clamp(index + 1, 0, size - 1));
                }
                return true;
            }
        }

        return false;
    }
}
