upd: replace the word state by country when used in country context
[gigi.git] / src / org / cacert / gigi / output / CountrySelector.java
1 package org.cacert.gigi.output;
2
3 import java.io.PrintWriter;
4 import java.util.List;
5 import java.util.Map;
6
7 import javax.servlet.http.HttpServletRequest;
8
9 import org.cacert.gigi.GigiApiException;
10 import org.cacert.gigi.dbObjects.Country;
11 import org.cacert.gigi.dbObjects.Country.CountryCodeType;
12 import org.cacert.gigi.localisation.Language;
13 import org.cacert.gigi.output.template.Outputable;
14 import org.cacert.gigi.output.template.Template;
15
16 public class CountrySelector implements Outputable {
17
18     private static final Template t = new Template(CountrySelector.class.getResource("CountrySelector.templ"));
19
20     private List<Country> all = Country.getCountries();
21
22     private String name;
23
24     private Country selected;
25
26     private boolean optional;
27
28     public CountrySelector(String name, boolean optional) {
29         this.name = name;
30         this.optional = optional;
31     }
32
33     public CountrySelector(String name, boolean optional, Country country) {
34         this(name, optional);
35         selected = country;
36     }
37
38     public void update(HttpServletRequest r) throws GigiApiException {
39         String vS = r.getParameter(name);
40
41         selected = null;
42
43         if (vS == null || vS.equals("invalid")) {
44             if (optional) {
45                 return;
46             } else {
47                 throw new GigiApiException("Country code required.");
48             }
49         }
50
51         selected = Country.getCountryByCode(vS, CountryCodeType.CODE_2_CHARS);
52     }
53
54     @Override
55     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
56         vars.put("countryCode", new IterableIterable<Country>(all) {
57
58             @Override
59             public void apply(Country t, Language l, Map<String, Object> vars) {
60                 vars.put("cc", t.getCode());
61                 vars.put("display", t.getName());
62                 if (selected != null && t.getCode().equals(selected.getCode())) {
63                     vars.put("selected", "selected");
64                 } else {
65                     vars.put("selected", "");
66                 }
67             }
68
69         });
70
71         vars.put("optional", optional);
72         vars.put("name", name);
73
74         t.output(out, l, vars);
75     }
76
77     public Country getCountry() {
78         return selected;
79     }
80
81 }