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