]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
notify the profile list adapter when a profile is changed
[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                 if (oldList == null) throw new AssertionError();
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         if (profiles == null) throw new AssertionError();
148         profiles.set(index, newProfile);
149
150         ProfilesRecyclerViewAdapter prva = ProfilesRecyclerViewAdapter.getInstance();
151         if (prva != null) prva.notifyItemChanged(index);
152
153         if (mProfile.equals(Data.profile.getValue())) Data.profile.setValue(newProfile);
154     }
155     @Override
156     public void onCreate(Bundle savedInstanceState) {
157         super.onCreate(savedInstanceState);
158
159         if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
160             int index = getArguments().getInt(ARG_ITEM_ID, -1);
161             ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
162             if ((profiles != null) && (index != -1) && (index < profiles.size()))
163                 mProfile = profiles.get(index);
164
165             Activity activity = this.getActivity();
166             if (activity == null) throw new AssertionError();
167             CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
168             if (appBarLayout != null) {
169                 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
170                 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
171             }
172         }
173     }
174     @Override
175     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
176         super.onActivityCreated(savedInstanceState);
177         Activity context = getActivity();
178         if (context == null) return;
179
180         FloatingActionButton fab = context.findViewById(R.id.fab);
181         fab.setOnClickListener(v -> onSaveFabClicked());
182
183         profileName.requestFocus();
184     }
185     private void onSaveFabClicked() {
186         if (!checkValidity()) return;
187
188         if (mProfile != null) {
189             updateProfileFromUI();
190 //                debug("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
191             mProfile.storeInDB();
192             debug("profiles", "profile stored in DB");
193             triggerProfileChange();
194         }
195         else {
196             mProfile = new MobileLedgerProfile();
197             updateProfileFromUI();
198             mProfile.storeInDB();
199             final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
200             if (profiles == null) throw new AssertionError();
201             ArrayList<MobileLedgerProfile> newList =
202                     (ArrayList<MobileLedgerProfile>) profiles.clone();
203             newList.add(mProfile);
204             Data.profiles.setValue(newList);
205             MobileLedgerProfile.storeProfilesOrder();
206
207             // first profile ever?
208             if (newList.size() == 1) Data.profile.setValue(mProfile);
209         }
210
211         Activity activity = getActivity();
212         if (activity != null) activity.finish();
213     }
214     private void updateProfileFromUI() {
215         mProfile.setName(profileName.getText());
216         mProfile.setUrl(url.getText());
217         mProfile.setPostingPermitted(postingPermitted.isChecked());
218         mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
219         mProfile.setAuthEnabled(useAuthentication.isChecked());
220         mProfile.setAuthUserName(userName.getText());
221         mProfile.setAuthPassword(password.getText());
222         mProfile.setThemeId(huePickerView.getTag());
223     }
224     @Override
225     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
226                              Bundle savedInstanceState) {
227         View rootView = inflater.inflate(R.layout.profile_detail, container, false);
228
229         profileName = rootView.findViewById(R.id.profile_name);
230         profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
231         url = rootView.findViewById(R.id.url);
232         urlLayout = rootView.findViewById(R.id.url_layout);
233         postingPermitted = rootView.findViewById(R.id.profile_permit_posting);
234         authParams = rootView.findViewById(R.id.auth_params);
235         useAuthentication = rootView.findViewById(R.id.enable_http_auth);
236         userName = rootView.findViewById(R.id.auth_user_name);
237         userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
238         password = rootView.findViewById(R.id.password);
239         passwordLayout = rootView.findViewById(R.id.password_layout);
240         huePickerView = rootView.findViewById(R.id.btn_pick_ring_color);
241         preferredAccountsFilter = rootView.findViewById(R.id.preferred_accounts_filter_filter);
242         preferredAccountsFilterLayout =
243                 rootView.findViewById(R.id.preferred_accounts_accounts_filter_layout);
244
245         useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
246             debug("profiles", isChecked ? "auth enabled " : "auth disabled");
247             authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
248             if (isChecked) userName.requestFocus();
249         });
250
251         postingPermitted.setOnCheckedChangeListener(
252                 ((buttonView, isChecked) -> preferredAccountsFilterLayout
253                         .setVisibility(isChecked ? View.VISIBLE : View.GONE)));
254
255         hookClearErrorOnFocusListener(profileName, profileNameLayout);
256         hookClearErrorOnFocusListener(url, urlLayout);
257         hookClearErrorOnFocusListener(userName, userNameLayout);
258         hookClearErrorOnFocusListener(password, passwordLayout);
259
260         int profileThemeId;
261         if (mProfile != null) {
262             profileName.setText(mProfile.getName());
263             postingPermitted.setChecked(mProfile.isPostingPermitted());
264             url.setText(mProfile.getUrl());
265             useAuthentication.setChecked(mProfile.isAuthEnabled());
266             authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
267             userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
268             password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
269             preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
270             profileThemeId = mProfile.getThemeId();
271         }
272         else {
273             profileName.setText("");
274             url.setText("https://");
275             postingPermitted.setChecked(true);
276             useAuthentication.setChecked(false);
277             authParams.setVisibility(View.GONE);
278             userName.setText("");
279             password.setText("");
280             preferredAccountsFilter.setText(null);
281             profileThemeId = -1;
282         }
283
284         final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
285         final int profileColor = Colors.getPrimaryColorForHue(hue);
286
287         huePickerView.setBackgroundColor(profileColor);
288         huePickerView.setTag(profileThemeId);
289         huePickerView.setOnClickListener(v -> {
290             HueRingDialog d = new HueRingDialog(
291                     Objects.requireNonNull(ProfileDetailFragment.this.getContext()), profileThemeId,
292                     (Integer) v.getTag());
293             d.show();
294             d.setColorSelectedListener(this);
295         });
296         return rootView;
297     }
298     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
299         view.setOnFocusChangeListener((v, hasFocus) -> {
300             if (hasFocus) layout.setError(null);
301         });
302         view.addTextChangedListener(new TextWatcher() {
303             @Override
304             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
305             }
306             @Override
307             public void onTextChanged(CharSequence s, int start, int before, int count) {
308                 layout.setError(null);
309             }
310             @Override
311             public void afterTextChanged(Editable s) {
312             }
313         });
314     }
315     private boolean checkValidity() {
316         boolean valid = true;
317
318         String val = String.valueOf(profileName.getText());
319         if (val.trim().isEmpty()) {
320             valid = false;
321             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
322         }
323
324         val = String.valueOf(url.getText());
325         if (val.trim().isEmpty()) {
326             valid = false;
327             urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
328         }
329         if (useAuthentication.isChecked()) {
330             val = String.valueOf(userName.getText());
331             if (val.trim().isEmpty()) {
332                 valid = false;
333                 userNameLayout
334                         .setError(getResources().getText(R.string.err_profile_user_name_empty));
335             }
336
337             val = String.valueOf(password.getText());
338             if (val.trim().isEmpty()) {
339                 valid = false;
340                 passwordLayout
341                         .setError(getResources().getText(R.string.err_profile_password_empty));
342             }
343         }
344
345         return valid;
346     }
347     @Override
348     public void onHueSelected(int hue) {
349         huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
350         huePickerView.setTag(hue);
351     }
352 }