001package state.ui;
002
003import java.io.BufferedReader;
004import java.io.IOException;
005import java.io.InputStreamReader;
006import java.io.PrintStream;
007
008final class TextUI implements UI {
009        final BufferedReader in;
010        final PrintStream out;
011
012        TextUI() {
013                in = new BufferedReader(new InputStreamReader(System.in));
014                out = System.out;
015        }
016
017        public void displayMessage(String message) {
018                out.println(message);
019        }
020
021        public void displayError(String message) {
022                out.println(message);
023        }
024
025        public Object processMenu(UIMenu menu) {
026                out.println(menu.getHeading());
027                out.println("Enter choice by number:");
028
029                for (int i = 1; i < menu.size(); i++) {
030                        out.println("  " + i + ". " + menu.getPrompt(i));
031                }
032
033                String responseString;
034
035                try {
036                        responseString = in.readLine();
037                } catch (IOException e) {
038                        throw new UIError(); // re-throw UIError
039                }
040                if (responseString == null) {
041                        throw new UIError(); // input closed
042                }
043
044                int selection;
045                try {
046                        selection = Integer.parseInt(responseString, 10);
047                        if ((selection < 0) || (selection >= menu.size()))
048                                selection = 0;
049                } catch (NumberFormatException e) {
050                        selection = 0;
051                }
052
053                return menu.runAction(selection);
054        }
055
056        public String[] processForm(UIForm form) {
057                // TODO
058                return null;
059        }
060}