]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
470a3eaee682e99ae0c436e28466059ef90f207e
[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.Switch;
33 import android.widget.TextView;
34
35 import com.google.android.material.appbar.CollapsingToolbarLayout;
36 import com.google.android.material.floatingactionbutton.FloatingActionButton;
37 import com.google.android.material.textfield.TextInputLayout;
38
39 import net.ktnx.mobileledger.BuildConfig;
40 import net.ktnx.mobileledger.R;
41 import net.ktnx.mobileledger.model.Data;
42 import net.ktnx.mobileledger.model.MobileLedgerProfile;
43 import net.ktnx.mobileledger.ui.HueRingDialog;
44 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
45 import net.ktnx.mobileledger.utils.Colors;
46
47 import org.jetbrains.annotations.NotNull;
48
49 import java.util.ArrayList;
50 import java.util.Objects;
51
52 import androidx.annotation.NonNull;
53 import androidx.annotation.Nullable;
54 import androidx.fragment.app.Fragment;
55 import androidx.fragment.app.FragmentActivity;
56
57 import static net.ktnx.mobileledger.utils.Logger.debug;
58
59 /**
60  * A fragment representing a single Profile detail screen.
61  * a {@link ProfileDetailActivity}
62  * on handsets.
63  */
64 public class ProfileDetailFragment extends Fragment implements HueRingDialog.HueSelectedListener {
65     /**
66      * The fragment argument representing the item ID that this fragment
67      * represents.
68      */
69     public static final String ARG_ITEM_ID = "item_id";
70
71     /**
72      * The dummy content this fragment is presenting.
73      */
74     private MobileLedgerProfile mProfile;
75     private TextView url;
76     private Switch postingPermitted;
77     private TextInputLayout urlLayout;
78     private LinearLayout authParams;
79     private Switch useAuthentication;
80     private TextView userName;
81     private TextInputLayout userNameLayout;
82     private TextView password;
83     private TextInputLayout passwordLayout;
84     private TextView profileName;
85     private TextInputLayout profileNameLayout;
86     private TextView preferredAccountsFilter;
87     private TextInputLayout preferredAccountsFilterLayout;
88     private View huePickerView;
89
90     /**
91      * Mandatory empty constructor for the fragment manager to instantiate the
92      * fragment (e.g. upon screen orientation changes).
93      */
94     public ProfileDetailFragment() {
95     }
96     @Override
97     public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
98         debug("profiles", "[fragment] Creating profile details options menu");
99         super.onCreateOptionsMenu(menu, inflater);
100         inflater.inflate(R.menu.profile_details, menu);
101         final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
102         menuDeleteProfile.setOnMenuItemClickListener(item -> {
103             AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
104             builder.setTitle(mProfile.getName());
105             builder.setMessage(R.string.remove_profile_dialog_message);
106             builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
107                 debug("profiles",
108                         String.format("[fragment] removing profile %s", mProfile.getUuid()));
109                 mProfile.removeFromDB();
110                 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
111                 assert oldList != null;
112                 ArrayList<MobileLedgerProfile> newList =
113                         (ArrayList<MobileLedgerProfile>) oldList.clone();
114                 newList.remove(mProfile);
115                 Data.profiles.setValue(newList);
116                 if (mProfile.equals(Data.profile.getValue())) {
117                     debug("profiles", "[fragment] setting current profile to 0");
118                     Data.setCurrentProfile(newList.get(0));
119                 }
120
121                 final FragmentActivity activity = getActivity();
122                 if (activity != null) activity.finish();
123             });
124             builder.show();
125             return false;
126         });
127         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
128         menuDeleteProfile
129                 .setVisible((mProfile != null) && (profiles != null) && (profiles.size() > 1));
130
131         if (BuildConfig.DEBUG) {
132             final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
133             menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
134             menuWipeProfileData.setVisible(mProfile != null);
135         }
136     }
137     private boolean onWipeDataMenuClicked() {
138         // this is a development option, so no confirmation
139         mProfile.wipeAllData();
140         if (mProfile.equals(Data.profile.getValue())) triggerProfileChange();
141         return true;
142     }
143     private void triggerProfileChange() {
144         int index = Data.getProfileIndex(mProfile);
145         MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
146         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
147         assert profiles != null;
148         profiles.set(index, newProfile);
149         if (mProfile.equals(Data.profile.getValue())) Data.profile.setValue(newProfile);
150     }
151     @Override
152     public void onCreate(Bundle savedInstanceState) {
153         super.onCreate(savedInstanceState);
154
155         if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
156             int index = getArguments().getInt(ARG_ITEM_ID, -1);
157             ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
158             if ((profiles != null) && (index != -1) && (index < profiles.size()))
159                 mProfile = profiles.get(index);
160
161             Activity activity = this.getActivity();
162             if (activity == null) throw new AssertionError();
163             CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
164             if (appBarLayout != null) {
165                 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
166                 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
167             }
168         }
169     }
170     @Override
171     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
172         super.onActivityCreated(savedInstanceState);
173         Activity context = getActivity();
174         if (context == null) return;
175
176         FloatingActionButton fab = context.findViewById(R.id.fab);
177         fab.setOnClickListener(v -> onSaveFabClicked());
178
179         profileName.requestFocus();
180     }
181     private void onSaveFabClicked() {
182         if (!checkValidity()) return;
183
184         if (mProfile != null) {
185             updateProfileFromUI();
186 //                debug("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
187             mProfile.storeInDB();
188             debug("profiles", "profile stored in DB");
189             triggerProfileChange();
190         }
191         else {
192             mProfile = new MobileLedgerProfile();
193             updateProfileFromUI();
194             mProfile.storeInDB();
195             final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
196             assert profiles != null;
197             ArrayList<MobileLedgerProfile> newList =
198                     (ArrayList<MobileLedgerProfile>) profiles.clone();
199             newList.add(mProfile);
200             Data.profiles.setValue(newList);
201             MobileLedgerProfile.storeProfilesOrder();
202
203             // first profile ever?
204             if (newList.size() == 1) Data.profile.setValue(mProfile);
205         }
206
207         Activity activity = getActivity();
208         if (activity != null) activity.finish();
209     }
210     private void updateProfileFromUI() {
211         mProfile.setName(profileName.getText());
212         mProfile.setUrl(url.getText());
213         mProfile.setPostingPermitted(postingPermitted.isChecked());
214         mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
215         mProfile.setAuthEnabled(useAuthentication.isChecked());
216         mProfile.setAuthUserName(userName.getText());
217         mProfile.setAuthPassword(password.getText());
218         mProfile.setThemeId(huePickerView.getTag());
219     }
220     @Override
221     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
222                              Bundle savedInstanceState) {
223         View rootView = inflater.inflate(R.layout.profile_detail, container, false);
224
225         profileName = rootView.findViewById(R.id.profile_name);
226         profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
227         url = rootView.findViewById(R.id.url);
228         urlLayout = rootView.findViewById(R.id.url_layout);
229         postingPermitted = rootView.findViewById(R.id.profile_permit_posting);
230         authParams = rootView.findViewById(R.id.auth_params);
231         useAuthentication = rootView.findViewById(R.id.enable_http_auth);
232         userName = rootView.findViewById(R.id.auth_user_name);
233         userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
234         password = rootView.findViewById(R.id.password);
235         passwordLayout = rootView.findViewById(R.id.password_layout);
236         huePickerView = rootView.findViewById(R.id.btn_pick_ring_color);
237         preferredAccountsFilter = rootView.findViewById(R.id.preferred_accounts_filter_filter);
238         preferredAccountsFilterLayout =
239                 rootView.findViewById(R.id.preferred_accounts_accounts_filter_layout);
240
241         useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
242             debug("profiles", isChecked ? "auth enabled " : "auth disabled");
243             authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
244             if (isChecked) userName.requestFocus();
245         });
246
247         postingPermitted.setOnCheckedChangeListener(
248                 ((buttonView, isChecked) -> preferredAccountsFilterLayout
249                         .setVisibility(isChecked ? View.VISIBLE : View.GONE)));
250
251         hookClearErrorOnFocusListener(profileName, profileNameLayout);
252         hookClearErrorOnFocusListener(url, urlLayout);
253         hookClearErrorOnFocusListener(userName, userNameLayout);
254         hookClearErrorOnFocusListener(password, passwordLayout);
255
256         int profileThemeId;
257         if (mProfile != null) {
258             profileName.setText(mProfile.getName());
259             postingPermitted.setChecked(mProfile.isPostingPermitted());
260             url.setText(mProfile.getUrl());
261             useAuthentication.setChecked(mProfile.isAuthEnabled());
262             authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
263             userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
264             password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
265             preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
266             profileThemeId = mProfile.getThemeId();
267         }
268         else {
269             profileName.setText("");
270             url.setText("https://");
271             postingPermitted.setChecked(true);
272             useAuthentication.setChecked(false);
273             authParams.setVisibility(View.GONE);
274             userName.setText("");
275             password.setText("");
276             preferredAccountsFilter.setText(null);
277             profileThemeId = -1;
278         }
279
280         final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
281         final int profileColor = Colors.getPrimaryColorForHue(hue);
282
283         huePickerView.setBackgroundColor(profileColor);
284         huePickerView.setTag(profileThemeId);
285         huePickerView.setOnClickListener(v -> {
286             HueRingDialog d = new HueRingDialog(
287                     Objects.requireNonNull(ProfileDetailFragment.this.getContext()), profileThemeId,
288                     (Integer) v.getTag());
289             d.show();
290             d.setColorSelectedListener(this);
291         });
292         return rootView;
293     }
294     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
295         view.setOnFocusChangeListener((v, hasFocus) -> {
296             if (hasFocus) layout.setError(null);
297         });
298         view.addTextChangedListener(new TextWatcher() {
299             @Override
300             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
301             }
302             @Override
303             public void onTextChanged(CharSequence s, int start, int before, int count) {
304                 layout.setError(null);
305             }
306             @Override
307             public void afterTextChanged(Editable s) {
308             }
309         });
310     }
311     private boolean checkValidity() {
312         boolean valid = true;
313
314         String val = String.valueOf(profileName.getText());
315         if (val.trim().isEmpty()) {
316             valid = false;
317             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
318         }
319
320         val = String.valueOf(url.getText());
321         if (val.trim().isEmpty()) {
322             valid = false;
323             urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
324         }
325         if (useAuthentication.isChecked()) {
326             val = String.valueOf(userName.getText());
327             if (val.trim().isEmpty()) {
328                 valid = false;
329                 userNameLayout
330                         .setError(getResources().getText(R.string.err_profile_user_name_empty));
331             }
332
333             val = String.valueOf(password.getText());
334             if (val.trim().isEmpty()) {
335                 valid = false;
336                 passwordLayout
337                         .setError(getResources().getText(R.string.err_profile_password_empty));
338             }
339         }
340
341         return valid;
342     }
343     @Override
344     public void onHueSelected(int hue) {
345         huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
346         huePickerView.setTag(hue);
347     }
348 }