1package eu.siacs.conversations.ui.forms;
2
3import android.content.Context;
4import android.support.v4.content.ContextCompat;
5import android.text.SpannableString;
6import android.text.style.ForegroundColorSpan;
7import android.text.style.StyleSpan;
8import android.util.Log;
9import android.view.LayoutInflater;
10import android.view.View;
11
12import java.util.List;
13
14import eu.siacs.conversations.Config;
15import eu.siacs.conversations.R;
16import eu.siacs.conversations.xmpp.forms.Field;
17
18public abstract class FormFieldWrapper {
19
20 protected final Context context;
21 protected final Field field;
22 protected final View view;
23 protected OnFormFieldValuesEdited onFormFieldValuesEditedListener;
24
25 protected FormFieldWrapper(Context context, Field field) {
26 this.context = context;
27 this.field = field;
28 LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
29 this.view = inflater.inflate(getLayoutResource(), null);
30 String label = field.getLabel();
31 if (label == null) {
32 label = field.getFieldName();
33 }
34 setLabel(label, field.isRequired());
35 }
36
37 public final void submit() {
38 this.field.setValues(getValues());
39 }
40
41 public final View getView() {
42 return view;
43 }
44
45 protected abstract void setLabel(String label, boolean required);
46
47 abstract List<String> getValues();
48
49 protected abstract void setValues(List<String> values);
50
51 abstract boolean validates();
52
53 abstract protected int getLayoutResource();
54
55 abstract void setReadOnly(boolean readOnly);
56
57 protected SpannableString createSpannableLabelString(String label, boolean required) {
58 SpannableString spannableString = new SpannableString(label + (required ? " *" : ""));
59 if (required) {
60 int start = label.length();
61 int end = label.length() + 2;
62 spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, end, 0);
63 spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.accent)), start, end, 0);
64 }
65 return spannableString;
66 }
67
68 protected void invokeOnFormFieldValuesEdited() {
69 if (this.onFormFieldValuesEditedListener != null) {
70 this.onFormFieldValuesEditedListener.onFormFieldValuesEdited();
71 }
72 }
73
74 public boolean edited() {
75 return !field.getValues().equals(getValues());
76 }
77
78 public void setOnFormFieldValuesEditedListener(OnFormFieldValuesEdited listener) {
79 this.onFormFieldValuesEditedListener = listener;
80 }
81
82 protected static <F extends FormFieldWrapper> FormFieldWrapper createFromField(Class<F> c, Context context, Field field) {
83 try {
84 F fieldWrapper = c.getDeclaredConstructor(Context.class, Field.class).newInstance(context,field);
85 fieldWrapper.setValues(field.getValues());
86 return fieldWrapper;
87 } catch (Exception e) {
88 e.printStackTrace();
89 return null;
90 }
91 }
92
93 public interface OnFormFieldValuesEdited {
94 void onFormFieldValuesEdited();
95 }
96}