package market.guess.ui.console; import java.util.Comparator; import java.util.List; import market.guess.ui.console.command.MenuCommand; import market.guess.ui.console.io.InputProcessor; import org.picocontainer.Startable; public final class Menu implements Startable { private final InputProcessor io; private final List commands; public Menu(List commands, InputProcessor io) { this.commands = commands.stream().sorted(Comparator.comparingInt(MenuCommand::getIndex)).toList(); this.io = io; } @Override public void start() { var max = commands.stream().mapToInt(MenuCommand::getIndex).max().orElse(0); io.splashScreen(); while (true) { io.newLine(); for (var command : commands) { io.println(" [%d]->> %s".formatted(command.getIndex(), command.getName())); } io.newLine(); var selection = io.readInt("Choose a command: ", 1, max); var commandOptional = commands.stream().filter(c -> c.getIndex() == selection).findFirst(); if (commandOptional.isEmpty()) { io.println("There is no command %d.".formatted(selection)); continue; } var command = commandOptional.get(); command.execute(); if (command.isExit()) { break; } } } @Override public void stop() { // Do nothing. } }