]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
themeId -> themeHue
[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 MoLe.
4  * MoLe 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  * MoLe 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 MoLe. 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.app.AlertDialog;
22 import android.os.Bundle;
23 import android.text.Editable;
24 import android.text.TextWatcher;
25 import android.view.LayoutInflater;
26 import android.view.Menu;
27 import android.view.MenuInflater;
28 import android.view.MenuItem;
29 import android.view.View;
30 import android.view.ViewGroup;
31 import android.widget.LinearLayout;
32 import android.widget.PopupMenu;
33 import android.widget.Switch;
34 import android.widget.TextView;
35
36 import androidx.annotation.NonNull;
37 import androidx.annotation.Nullable;
38 import androidx.fragment.app.Fragment;
39 import androidx.fragment.app.FragmentActivity;
40
41 import com.google.android.material.appbar.CollapsingToolbarLayout;
42 import com.google.android.material.floatingactionbutton.FloatingActionButton;
43 import com.google.android.material.textfield.TextInputLayout;
44
45 import net.ktnx.mobileledger.BuildConfig;
46 import net.ktnx.mobileledger.R;
47 import net.ktnx.mobileledger.async.SendTransactionTask;
48 import net.ktnx.mobileledger.model.Data;
49 import net.ktnx.mobileledger.model.MobileLedgerProfile;
50 import net.ktnx.mobileledger.ui.HueRingDialog;
51 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
52 import net.ktnx.mobileledger.utils.Colors;
53
54 import org.jetbrains.annotations.NonNls;
55 import org.jetbrains.annotations.NotNull;
56
57 import java.net.MalformedURLException;
58 import java.net.URL;
59 import java.util.ArrayList;
60 import java.util.Objects;
61
62 import static net.ktnx.mobileledger.utils.Logger.debug;
63
64 /**
65  * A fragment representing a single Profile detail screen.
66  * a {@link ProfileDetailActivity}
67  * on handsets.
68  */
69 public class ProfileDetailFragment extends Fragment implements HueRingDialog.HueSelectedListener {
70     /**
71      * The fragment argument representing the item ID that this fragment
72      * represents.
73      */
74     public static final String ARG_ITEM_ID = "item_id";
75     @NonNls
76     private static final String HTTPS_URL_START = "https://";
77
78     /**
79      * The dummy content this fragment is presenting.
80      */
81     private MobileLedgerProfile mProfile;
82     private TextView url;
83     private Switch postingPermitted;
84     private TextInputLayout urlLayout;
85     private LinearLayout authParams;
86     private Switch useAuthentication;
87     private TextView userName;
88     private TextInputLayout userNameLayout;
89     private TextView password;
90     private TextInputLayout passwordLayout;
91     private TextView profileName;
92     private TextInputLayout profileNameLayout;
93     private TextView preferredAccountsFilter;
94     private TextInputLayout preferredAccountsFilterLayout;
95     private View huePickerView;
96     private View insecureWarningText;
97     private TextView futureDatesText;
98     private MobileLedgerProfile.FutureDates futureDates;
99     private View futureDatesLayout;
100     private TextView apiVersionText;
101     private SendTransactionTask.API apiVersion;
102
103     /**
104      * Mandatory empty constructor for the fragment manager to instantiate the
105      * fragment (e.g. upon screen orientation changes).
106      */
107     public ProfileDetailFragment() {
108     }
109     @Override
110     public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
111         debug("profiles", "[fragment] Creating profile details options menu");
112         super.onCreateOptionsMenu(menu, inflater);
113         inflater.inflate(R.menu.profile_details, menu);
114         final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
115         menuDeleteProfile.setOnMenuItemClickListener(item -> {
116             AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
117             builder.setTitle(mProfile.getName());
118             builder.setMessage(R.string.remove_profile_dialog_message);
119             builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
120                 debug("profiles",
121                         String.format("[fragment] removing profile %s", mProfile.getUuid()));
122                 mProfile.removeFromDB();
123                 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
124                 if (oldList == null)
125                     throw new AssertionError();
126                 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
127                 newList.remove(mProfile);
128                 Data.profiles.setValue(newList);
129                 if (mProfile.equals(Data.profile.getValue())) {
130                     debug("profiles", "[fragment] setting current profile to 0");
131                     Data.setCurrentProfile(newList.get(0));
132                 }
133
134                 final FragmentActivity activity = getActivity();
135                 if (activity != null)
136                     activity.finish();
137             });
138             builder.show();
139             return false;
140         });
141         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
142         menuDeleteProfile.setVisible(
143                 (mProfile != null) && (profiles != null) && (profiles.size() > 1));
144
145         if (BuildConfig.DEBUG) {
146             final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
147             menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
148             menuWipeProfileData.setVisible(mProfile != null);
149         }
150     }
151     private boolean onWipeDataMenuClicked() {
152         // this is a development option, so no confirmation
153         mProfile.wipeAllData();
154         if (mProfile.equals(Data.profile.getValue()))
155             triggerProfileChange();
156         return true;
157     }
158     private void triggerProfileChange() {
159         int index = Data.getProfileIndex(mProfile);
160         MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
161         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
162         if (profiles == null)
163             throw new AssertionError();
164         profiles.set(index, newProfile);
165
166         ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
167         if (viewAdapter != null)
168             viewAdapter.notifyItemChanged(index);
169
170         if (mProfile.equals(Data.profile.getValue()))
171             Data.profile.setValue(newProfile);
172     }
173     @Override
174     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
175         super.onActivityCreated(savedInstanceState);
176         Activity context = getActivity();
177         if (context == null)
178             return;
179
180         if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
181             int index = getArguments().getInt(ARG_ITEM_ID, -1);
182             ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
183             if ((profiles != null) && (index != -1) && (index < profiles.size()))
184                 mProfile = profiles.get(index);
185
186             Activity activity = this.getActivity();
187             if (activity == null)
188                 throw new AssertionError();
189             CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
190             if (appBarLayout != null) {
191                 if (mProfile != null)
192                     appBarLayout.setTitle(mProfile.getName());
193                 else
194                     appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
195             }
196         }
197
198         FloatingActionButton fab = context.findViewById(R.id.fab);
199         fab.setOnClickListener(v -> onSaveFabClicked());
200         profileName = context.findViewById(R.id.profile_name);
201         profileNameLayout = context.findViewById(R.id.profile_name_layout);
202         url = context.findViewById(R.id.url);
203         urlLayout = context.findViewById(R.id.url_layout);
204         postingPermitted = context.findViewById(R.id.profile_permit_posting);
205         futureDatesLayout = context.findViewById(R.id.future_dates_layout);
206         futureDatesText = context.findViewById(R.id.future_dates_text);
207         context.findViewById(R.id.future_dates_layout)
208                .setOnClickListener(v -> {
209                    MenuInflater mi = new MenuInflater(context);
210                    PopupMenu menu = new PopupMenu(context, v);
211                    menu.inflate(R.menu.future_dates);
212                    menu.setOnMenuItemClickListener(item -> {
213                        switch (item.getItemId()) {
214                            case R.id.menu_future_dates_30:
215                                futureDates = MobileLedgerProfile.FutureDates.OneMonth;
216                                break;
217                            case R.id.menu_future_dates_60:
218                                futureDates = MobileLedgerProfile.FutureDates.TwoMonths;
219                                break;
220                            case R.id.menu_future_dates_90:
221                                futureDates = MobileLedgerProfile.FutureDates.ThreeMonths;
222                                break;
223                            case R.id.menu_future_dates_180:
224                                futureDates = MobileLedgerProfile.FutureDates.SixMonths;
225                                break;
226                            case R.id.menu_future_dates_365:
227                                futureDates = MobileLedgerProfile.FutureDates.OneYear;
228                                break;
229                            case R.id.menu_future_dates_all:
230                                futureDates = MobileLedgerProfile.FutureDates.All;
231                                break;
232                            default:
233                                futureDates = MobileLedgerProfile.FutureDates.None;
234                        }
235                        futureDatesText.setText(futureDates.getText(getResources()));
236                        return true;
237                    });
238                    menu.show();
239                });
240         apiVersionText = context.findViewById(R.id.api_version_text);
241         context.findViewById(R.id.api_version_layout)
242                .setOnClickListener(v -> {
243                    MenuInflater mi = new MenuInflater(context);
244                    PopupMenu menu = new PopupMenu(context, v);
245                    menu.inflate(R.menu.api_version);
246                    menu.setOnMenuItemClickListener(item -> {
247                        switch (item.getItemId()) {
248                            case R.id.api_version_menu_html:
249                                apiVersion = SendTransactionTask.API.html;
250                                break;
251                            case R.id.api_version_menu_post_1_14:
252                                apiVersion = SendTransactionTask.API.post_1_14;
253                                break;
254                            case R.id.api_version_menu_pre_1_15:
255                                apiVersion = SendTransactionTask.API.pre_1_15;
256                                break;
257                            case R.id.api_version_menu_auto:
258                            default:
259                                apiVersion = SendTransactionTask.API.auto;
260                        }
261                        apiVersionText.setText(apiVersion.getDescription(getResources()));
262                        return true;
263                    });
264                    menu.show();
265                });
266         authParams = context.findViewById(R.id.auth_params);
267         useAuthentication = context.findViewById(R.id.enable_http_auth);
268         userName = context.findViewById(R.id.auth_user_name);
269         userNameLayout = context.findViewById(R.id.auth_user_name_layout);
270         password = context.findViewById(R.id.password);
271         passwordLayout = context.findViewById(R.id.password_layout);
272         huePickerView = context.findViewById(R.id.btn_pick_ring_color);
273         preferredAccountsFilter = context.findViewById(R.id.preferred_accounts_filter_filter);
274         preferredAccountsFilterLayout =
275                 context.findViewById(R.id.preferred_accounts_accounts_filter_layout);
276         insecureWarningText = context.findViewById(R.id.insecure_scheme_text);
277
278         useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
279             debug("profiles", isChecked ? "auth enabled " : "auth disabled");
280             authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
281             if (isChecked)
282                 userName.requestFocus();
283             checkInsecureSchemeWithAuth();
284         });
285
286         postingPermitted.setOnCheckedChangeListener(((buttonView, isChecked) -> {
287             preferredAccountsFilterLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
288             futureDatesLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
289         }));
290
291         hookClearErrorOnFocusListener(profileName, profileNameLayout);
292         hookClearErrorOnFocusListener(url, urlLayout);
293         hookClearErrorOnFocusListener(userName, userNameLayout);
294         hookClearErrorOnFocusListener(password, passwordLayout);
295
296         int profileThemeId;
297         if (mProfile != null) {
298             profileName.setText(mProfile.getName());
299             postingPermitted.setChecked(mProfile.isPostingPermitted());
300             futureDates = mProfile.getFutureDates();
301             futureDatesText.setText(futureDates.getText(getResources()));
302             apiVersion = mProfile.getApiVersion();
303             apiVersionText.setText(apiVersion.getDescription(getResources()));
304             url.setText(mProfile.getUrl());
305             useAuthentication.setChecked(mProfile.isAuthEnabled());
306             authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
307             userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
308             password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
309             preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
310             profileThemeId = mProfile.getThemeHue();
311         }
312         else {
313             profileName.setText("");
314             url.setText(HTTPS_URL_START);
315             postingPermitted.setChecked(true);
316             futureDates = MobileLedgerProfile.FutureDates.None;
317             futureDatesText.setText(futureDates.getText(getResources()));
318             apiVersion = SendTransactionTask.API.auto;
319             apiVersionText.setText(apiVersion.getDescription(getResources()));
320             useAuthentication.setChecked(false);
321             authParams.setVisibility(View.GONE);
322             userName.setText("");
323             password.setText("");
324             preferredAccountsFilter.setText(null);
325             profileThemeId = -1;
326         }
327
328         checkInsecureSchemeWithAuth();
329
330         url.addTextChangedListener(new TextWatcher() {
331             @Override
332             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
333
334             }
335             @Override
336             public void onTextChanged(CharSequence s, int start, int before, int count) {
337
338             }
339             @Override
340             public void afterTextChanged(Editable s) {
341                 checkInsecureSchemeWithAuth();
342             }
343         });
344
345         final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
346         final int profileColor = Colors.getPrimaryColorForHue(hue);
347
348         huePickerView.setBackgroundColor(profileColor);
349         huePickerView.setTag(profileThemeId);
350         huePickerView.setOnClickListener(v -> {
351             HueRingDialog d = new HueRingDialog(
352                     Objects.requireNonNull(ProfileDetailFragment.this.getContext()), profileThemeId,
353                     (Integer) v.getTag());
354             d.show();
355             d.setColorSelectedListener(this);
356         });
357
358         profileName.requestFocus();
359     }
360     private void onSaveFabClicked() {
361         if (!checkValidity())
362             return;
363
364         if (mProfile != null) {
365             updateProfileFromUI();
366 //                debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
367             mProfile.storeInDB();
368             debug("profiles", "profile stored in DB");
369             triggerProfileChange();
370         }
371         else {
372             mProfile = new MobileLedgerProfile();
373             updateProfileFromUI();
374             mProfile.storeInDB();
375             final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
376             if (profiles == null)
377                 throw new AssertionError();
378             ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
379             newList.add(mProfile);
380             Data.profiles.setValue(newList);
381             MobileLedgerProfile.storeProfilesOrder();
382
383             // first profile ever?
384             if (newList.size() == 1)
385                 Data.profile.setValue(mProfile);
386         }
387
388         Activity activity = getActivity();
389         if (activity != null)
390             activity.finish();
391     }
392     private void updateProfileFromUI() {
393         mProfile.setName(profileName.getText());
394         mProfile.setUrl(url.getText());
395         mProfile.setPostingPermitted(postingPermitted.isChecked());
396         mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
397         mProfile.setAuthEnabled(useAuthentication.isChecked());
398         mProfile.setAuthUserName(userName.getText());
399         mProfile.setAuthPassword(password.getText());
400         mProfile.setThemeHue(huePickerView.getTag());
401         mProfile.setFutureDates(futureDates);
402         mProfile.setApiVersion(apiVersion);
403     }
404     @Override
405     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
406                              Bundle savedInstanceState) {
407
408         return inflater.inflate(R.layout.profile_detail, container, false);
409     }
410     private boolean checkUrlValidity() {
411         boolean valid = true;
412
413         String val = String.valueOf(url.getText())
414                            .trim();
415         if (val.isEmpty()) {
416             valid = false;
417             urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
418         }
419         try {
420             URL url = new URL(val);
421             String host = url.getHost();
422             if (host == null || host.isEmpty())
423                 throw new MalformedURLException("Missing host");
424             String protocol = url.getProtocol()
425                                  .toUpperCase();
426             if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
427                 valid = false;
428                 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
429             }
430         }
431         catch (MalformedURLException e) {
432             valid = false;
433             urlLayout.setError(getResources().getText(R.string.err_invalid_url));
434         }
435
436         return valid;
437     }
438     private void checkInsecureSchemeWithAuth() {
439         boolean showWarning = false;
440
441         if (useAuthentication.isChecked()) {
442             String urlText = url.getText()
443                                 .toString();
444             if (urlText.startsWith("http") && !urlText.startsWith("https"))
445                 showWarning = true;
446         }
447
448         if (showWarning)
449             insecureWarningText.setVisibility(View.VISIBLE);
450         else
451             insecureWarningText.setVisibility(View.GONE);
452     }
453     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
454         view.setOnFocusChangeListener((v, hasFocus) -> {
455             if (hasFocus)
456                 layout.setError(null);
457         });
458         view.addTextChangedListener(new TextWatcher() {
459             @Override
460             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
461             }
462             @Override
463             public void onTextChanged(CharSequence s, int start, int before, int count) {
464                 layout.setError(null);
465             }
466             @Override
467             public void afterTextChanged(Editable s) {
468             }
469         });
470     }
471     private boolean checkValidity() {
472         boolean valid = true;
473
474         String val = String.valueOf(profileName.getText());
475         if (val.trim()
476                .isEmpty())
477         {
478             valid = false;
479             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
480         }
481
482         if (!checkUrlValidity())
483             valid = false;
484
485         if (useAuthentication.isChecked()) {
486             val = String.valueOf(userName.getText());
487             if (val.trim()
488                    .isEmpty())
489             {
490                 valid = false;
491                 userNameLayout.setError(
492                         getResources().getText(R.string.err_profile_user_name_empty));
493             }
494
495             val = String.valueOf(password.getText());
496             if (val.trim()
497                    .isEmpty())
498             {
499                 valid = false;
500                 passwordLayout.setError(
501                         getResources().getText(R.string.err_profile_password_empty));
502             }
503         }
504
505         return valid;
506     }
507     @Override
508     public void onHueSelected(int hue) {
509         huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
510         huePickerView.setTag(hue);
511     }
512 }