]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
profile details: validation on save
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / profiles / ProfileDetailFragment.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of Mobile-Ledger.
4  * Mobile-Ledger is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * Mobile-Ledger is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with Mobile-Ledger. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.profiles;
19
20 import android.app.Activity;
21 import android.os.Bundle;
22 import android.support.annotation.NonNull;
23 import android.support.annotation.Nullable;
24 import android.support.design.widget.CollapsingToolbarLayout;
25 import android.support.design.widget.FloatingActionButton;
26 import android.support.design.widget.TextInputLayout;
27 import android.support.v4.app.Fragment;
28 import android.text.Editable;
29 import android.text.TextWatcher;
30 import android.util.Log;
31 import android.view.LayoutInflater;
32 import android.view.Menu;
33 import android.view.MenuInflater;
34 import android.view.MenuItem;
35 import android.view.View;
36 import android.view.ViewGroup;
37 import android.widget.LinearLayout;
38 import android.widget.Switch;
39 import android.widget.TextView;
40
41 import net.ktnx.mobileledger.R;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.MobileLedgerProfile;
44 import net.ktnx.mobileledger.ui.activity.ProfileListActivity;
45
46 /**
47  * A fragment representing a single Profile detail screen.
48  * This fragment is either contained in a {@link ProfileListActivity}
49  * in two-pane mode (on tablets) or a {@link ProfileDetailActivity}
50  * on handsets.
51  */
52 public class ProfileDetailFragment extends Fragment {
53     /**
54      * The fragment argument representing the item ID that this fragment
55      * represents.
56      */
57     public static final String ARG_ITEM_ID = "item_id";
58
59     /**
60      * The dummy content this fragment is presenting.
61      */
62     private MobileLedgerProfile mProfile;
63     private TextView url;
64     private TextInputLayout urlLayout;
65     private LinearLayout authParams;
66     private Switch useAuthentication;
67     private TextView userName;
68     private TextInputLayout userNameLayout;
69     private TextView password;
70     private TextInputLayout passwordLayout;
71     private TextView profileName;
72     private TextInputLayout profileNameLayout;
73     private FloatingActionButton fab;
74
75     /**
76      * Mandatory empty constructor for the fragment manager to instantiate the
77      * fragment (e.g. upon screen orientation changes).
78      */
79     public ProfileDetailFragment() {
80     }
81     @Override
82     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
83         Log.d("profiles", "[fragment] Creating profile details options menu");
84         super.onCreateOptionsMenu(menu, inflater);
85         inflater.inflate(R.menu.profile_details, menu);
86         final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
87         menuDeleteProfile.setOnMenuItemClickListener(item -> {
88             Log.d("profiles", String.format("[fragment] removing profile %s", mProfile.getUuid()));
89             mProfile.removeFromDB();
90             Data.profiles.remove(mProfile);
91             if (Data.profile.get().equals(mProfile)) {
92                 Log.d("profiles", "[fragment] setting current profile to 0");
93                 Data.setCurrentProfile(Data.profiles.get(0));
94             }
95             return false;
96         });
97         menuDeleteProfile.setVisible((mProfile != null) && (Data.profiles.size() > 1));
98     }
99     @Override
100     public void onCreate(Bundle savedInstanceState) {
101         super.onCreate(savedInstanceState);
102
103         if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
104             int index = getArguments().getInt(ARG_ITEM_ID, -1);
105             if (index != -1) mProfile = Data.profiles.get(index);
106
107             Activity activity = this.getActivity();
108             if (activity == null) throw new AssertionError();
109             CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
110             if (appBarLayout != null) {
111                 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
112                 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
113             }
114         }
115     }
116     @Override
117     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
118         super.onActivityCreated(savedInstanceState);
119         Activity context = getActivity();
120         if (context == null) return;
121
122         fab = context.findViewById(R.id.fab);
123         fab.setOnClickListener(v -> {
124             if (!checkValidity()) return;
125
126             if (mProfile != null) {
127                 mProfile.setName(profileName.getText());
128                 mProfile.setUrl(url.getText());
129                 mProfile.setAuthEnabled(useAuthentication.isChecked());
130                 mProfile.setAuthUserName(userName.getText());
131                 mProfile.setAuthPassword(password.getText());
132                 mProfile.storeInDB();
133                 Log.d("profiles", "profile stored in DB");
134                 Data.profiles.triggerItemChangedNotification(mProfile);
135
136
137                 if (mProfile.getUuid().equals(Data.profile.get().getUuid())) {
138                     // dummy update to notify the observers of the possibly new name/URL
139                     Data.profile.set(mProfile);
140                 }
141             }
142             else {
143                 mProfile = new MobileLedgerProfile(profileName.getText(), url.getText(),
144                         useAuthentication.isChecked(), userName.getText(), password.getText());
145                 mProfile.storeInDB();
146                 Data.profiles.add(mProfile);
147                 MobileLedgerProfile.storeProfilesOrder();
148             }
149
150             Activity activity = getActivity();
151             if (activity != null) activity.finish();
152         });
153
154         profileName.requestFocus();
155     }
156     @Override
157     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
158                              Bundle savedInstanceState) {
159         View rootView = inflater.inflate(R.layout.profile_detail, container, false);
160
161         profileName = rootView.findViewById(R.id.profile_name);
162         profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
163         url = rootView.findViewById(R.id.url);
164         urlLayout = rootView.findViewById(R.id.url_layout);
165         authParams = rootView.findViewById(R.id.auth_params);
166         useAuthentication = rootView.findViewById(R.id.enable_http_auth);
167         userName = rootView.findViewById(R.id.auth_user_name);
168         userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
169         password = rootView.findViewById(R.id.password);
170         passwordLayout = rootView.findViewById(R.id.password_layout);
171
172         useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
173             Log.d("profiles", isChecked ? "auth enabled " : "auth disabled");
174             authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
175             if (isChecked) userName.requestFocus();
176         });
177
178         hookClearErrorOnFocusListener(profileName, profileNameLayout);
179         hookClearErrorOnFocusListener(url, urlLayout);
180         hookClearErrorOnFocusListener(userName, userNameLayout);
181         hookClearErrorOnFocusListener(password, passwordLayout);
182
183         if (mProfile != null) {
184             profileName.setText(mProfile.getName());
185             url.setText(mProfile.getUrl());
186             useAuthentication.setChecked(mProfile.isAuthEnabled());
187             authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
188             userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
189             password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
190         }
191         else {
192             profileName.setText("");
193             url.setText("");
194             useAuthentication.setChecked(false);
195             authParams.setVisibility(View.GONE);
196             userName.setText("");
197             password.setText("");
198         }
199
200         return rootView;
201     }
202     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
203         view.setOnFocusChangeListener((v, hasFocus) -> {
204             if (hasFocus) layout.setError(null);
205         });
206         view.addTextChangedListener(new TextWatcher() {
207             @Override
208             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
209             }
210             @Override
211             public void onTextChanged(CharSequence s, int start, int before, int count) {
212                 layout.setError(null);
213             }
214             @Override
215             public void afterTextChanged(Editable s) {
216             }
217         });
218     }
219     boolean checkValidity() {
220         boolean valid = true;
221
222         String val = String.valueOf(profileName.getText());
223         if (val.trim().isEmpty()) {
224             valid = false;
225             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
226         }
227
228         val = String.valueOf(url.getText());
229         if (val.trim().isEmpty()) {
230             valid = false;
231             urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
232         }
233         if (useAuthentication.isChecked()) {
234             val = String.valueOf(userName.getText());
235             if (val.trim().isEmpty()) {
236                 valid = false;
237                 userNameLayout
238                         .setError(getResources().getText(R.string.err_profile_user_name_empty));
239             }
240
241             val = String.valueOf(password.getText());
242             if (val.trim().isEmpty()) {
243                 valid = false;
244                 passwordLayout
245                         .setError(getResources().getText(R.string.err_profile_password_empty));
246             }
247         }
248
249         return valid;
250     }
251 }