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