aboutsummaryrefslogtreecommitdiffstats
path: root/ui-console/src/main/java/market/guess/ui/console/Menu.java
blob: b18d6fb5760871cb03816d2e00af65d80955f0d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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<MenuCommand> commands;

  public Menu(List<MenuCommand> 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.
  }
}