1package eu.siacs.conversations.xmpp.forms;
2
3import android.os.Bundle;
4
5import java.util.ArrayList;
6import java.util.Collection;
7import java.util.Iterator;
8import java.util.List;
9
10import eu.siacs.conversations.xml.Element;
11
12public class Data extends Element {
13
14 public static final String FORM_TYPE = "FORM_TYPE";
15
16 public Data() {
17 super("x");
18 this.setAttribute("xmlns","jabber:x:data");
19 }
20
21 public List<Field> getFields() {
22 ArrayList<Field> fields = new ArrayList<Field>();
23 for(Element child : getChildren()) {
24 if (child.getName().equals("field")
25 && !FORM_TYPE.equals(child.getAttribute("var"))) {
26 fields.add(Field.parse(child));
27 }
28 }
29 return fields;
30 }
31
32 public Field getFieldByName(String needle) {
33 for(Element child : getChildren()) {
34 if (child.getName().equals("field")
35 && needle.equals(child.getAttribute("var"))) {
36 return Field.parse(child);
37 }
38 }
39 return null;
40 }
41
42 public void put(String name, String value) {
43 Field field = getFieldByName(name);
44 if (field == null) {
45 field = new Field(name);
46 this.addChild(field);
47 }
48 field.setValue(value);
49 }
50
51 public void put(String name, Collection<String> values) {
52 Field field = getFieldByName(name);
53 if (field == null) {
54 field = new Field(name);
55 this.addChild(field);
56 }
57 field.setValues(values);
58 }
59
60 public void submit(Bundle options) {
61 for (Field field : getFields()) {
62 if (options.containsKey(field.getFieldName())) {
63 field.setValue(options.getString(field.getFieldName()));
64 }
65 }
66 submit();
67 }
68
69 public void submit() {
70 this.setAttribute("type","submit");
71 removeUnnecessaryChildren();
72 for(Field field : getFields()) {
73 field.removeNonValueChildren();
74 }
75 }
76
77 private void removeUnnecessaryChildren() {
78 for(Iterator<Element> iterator = this.children.iterator(); iterator.hasNext();) {
79 Element element = iterator.next();
80 if (!element.getName().equals("field") && !element.getName().equals("title")) {
81 iterator.remove();
82 }
83 }
84 }
85
86 public static Data parse(Element element) {
87 Data data = new Data();
88 data.setAttributes(element.getAttributes());
89 data.setChildren(element.getChildren());
90 return data;
91 }
92
93 public void setFormType(String formType) {
94 this.put(FORM_TYPE, formType);
95 }
96
97 public String getFormType() {
98 String type = getValue(FORM_TYPE);
99 return type == null ? "" : type;
100 }
101
102 public String getValue(String name) {
103 Field field = this.getFieldByName(name);
104 return field == null ? null : field.getValue();
105 }
106
107 public String getTitle() {
108 return findChildContent("title");
109 }
110
111}