1package autotest.afe;
2
3import java.util.ArrayList;
4import java.util.List;
5
6public class RadioChooser {
7    public static interface Display {
8        public IRadioButton generateRadioButton(String groupName, String choice);
9    }
10
11    private static int groupNameCounter = 0;
12    private String groupName = getFreshGroupName();
13    private List<IRadioButton> radioButtons = new ArrayList<IRadioButton>();
14    private IRadioButton defaultButton;
15
16    private Display display;
17
18    public void bindDisplay(Display display) {
19        this.display = display;
20    }
21
22    private static String getFreshGroupName() {
23        groupNameCounter++;
24        return "group" + Integer.toString(groupNameCounter);
25    }
26
27    public void addChoice(String choice) {
28        IRadioButton button = display.generateRadioButton(groupName, choice);
29        if (radioButtons.isEmpty()) {
30            // first button in this group
31            defaultButton = button;
32            button.setValue(true);
33        }
34        radioButtons.add(button);
35    }
36
37    public String getSelectedChoice() {
38        for (IRadioButton button : radioButtons) {
39            if (button.getValue()) {
40                return button.getText();
41            }
42        }
43        throw new RuntimeException("No radio button selected");
44    }
45
46    public void reset() {
47        if (defaultButton != null) {
48            defaultButton.setValue(true);
49        }
50    }
51
52    public void setDefaultChoice(String defaultChoice) {
53        defaultButton = findButtonForChoice(defaultChoice);
54    }
55
56    public void setSelectedChoice(String choice) {
57        findButtonForChoice(choice).setValue(true);
58    }
59
60    private IRadioButton findButtonForChoice(String choice) {
61        for (IRadioButton button : radioButtons) {
62            if (button.getText().equals(choice)) {
63                return button;
64            }
65        }
66        throw new RuntimeException("No such choice found: " + choice);
67    }
68}
69