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