]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
8ec74734b4e6b71c7ea1d8abdd17929f749045b6
[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",
105                             String.format("[fragment] removing profile %s", mProfile.getUuid()));
106                     mProfile.removeFromDB();
107                     Data.profiles.remove(mProfile);
108                     if (Data.profile.get().equals(mProfile)) {
109                         Log.d("profiles", "[fragment] setting current profile to 0");
110                         Data.setCurrentProfile(Data.profiles.get(0));
111                     }
112                     getActivity().finish();
113                 }
114             });
115             builder.show();
116             return false;
117         });
118         menuDeleteProfile.setVisible((mProfile != null) && (Data.profiles.size() > 1));
119     }
120     @Override
121     public void onCreate(Bundle savedInstanceState) {
122         super.onCreate(savedInstanceState);
123
124         if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
125             int index = getArguments().getInt(ARG_ITEM_ID, -1);
126             if (index != -1) mProfile = Data.profiles.get(index);
127
128             Activity activity = this.getActivity();
129             if (activity == null) throw new AssertionError();
130             CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
131             if (appBarLayout != null) {
132                 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
133                 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
134             }
135         }
136     }
137     @Override
138     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
139         super.onActivityCreated(savedInstanceState);
140         Activity context = getActivity();
141         if (context == null) return;
142
143         FloatingActionButton fab = context.findViewById(R.id.fab);
144         fab.setOnClickListener(v -> {
145             if (!checkValidity()) return;
146
147             if (mProfile != null) {
148                 updateProfileFromUI();
149 //                Log.d("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
150                 mProfile.storeInDB();
151                 Log.d("profiles", "profile stored in DB");
152                 Data.profiles.triggerItemChangedNotification(mProfile);
153
154
155                 if (mProfile.getUuid().equals(Data.profile.get().getUuid())) {
156                     // dummy update to notify the observers of the possibly new name/URL
157                     Data.profile.set(mProfile);
158                 }
159             }
160             else {
161                 mProfile = new MobileLedgerProfile();
162                 updateProfileFromUI();
163                 mProfile.storeInDB();
164                 Data.profiles.add(mProfile);
165                 MobileLedgerProfile.storeProfilesOrder();
166
167                 // first profile ever?
168                 if (Data.profiles.size() == 1) Data.profile.set(mProfile);
169             }
170
171             Activity activity = getActivity();
172             if (activity != null) activity.finish();
173         });
174
175         profileName.requestFocus();
176     }
177     private void updateProfileFromUI() {
178         mProfile.setName(profileName.getText());
179         mProfile.setUrl(url.getText());
180         mProfile.setPostingPermitted(postingPermitted.isChecked());
181         mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
182         mProfile.setAuthEnabled(useAuthentication.isChecked());
183         mProfile.setAuthUserName(userName.getText());
184         mProfile.setAuthPassword(password.getText());
185         mProfile.setThemeId(huePickerView.getTag());
186     }
187     @Override
188     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
189                              Bundle savedInstanceState) {
190         View rootView = inflater.inflate(R.layout.profile_detail, container, false);
191
192         profileName = rootView.findViewById(R.id.profile_name);
193         profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
194         url = rootView.findViewById(R.id.url);
195         urlLayout = rootView.findViewById(R.id.url_layout);
196         postingPermitted = rootView.findViewById(R.id.profile_permit_posting);
197         authParams = rootView.findViewById(R.id.auth_params);
198         useAuthentication = rootView.findViewById(R.id.enable_http_auth);
199         userName = rootView.findViewById(R.id.auth_user_name);
200         userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
201         password = rootView.findViewById(R.id.password);
202         passwordLayout = rootView.findViewById(R.id.password_layout);
203         huePickerView = rootView.findViewById(R.id.btn_pick_ring_color);
204         preferredAccountsFilter = rootView.findViewById(R.id.preferred_accounts_filter_filter);
205         preferredAccountsFilterLayout =
206                 rootView.findViewById(R.id.preferred_accounts_accounts_filter_layout);
207
208         useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
209             Log.d("profiles", isChecked ? "auth enabled " : "auth disabled");
210             authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
211             if (isChecked) userName.requestFocus();
212         });
213
214         preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
215         postingPermitted.setOnCheckedChangeListener(((buttonView, isChecked) -> {
216             preferredAccountsFilterLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
217         }));
218
219         hookClearErrorOnFocusListener(profileName, profileNameLayout);
220         hookClearErrorOnFocusListener(url, urlLayout);
221         hookClearErrorOnFocusListener(userName, userNameLayout);
222         hookClearErrorOnFocusListener(password, passwordLayout);
223
224         int profileThemeId;
225         if (mProfile != null) {
226             profileName.setText(mProfile.getName());
227             postingPermitted.setChecked(mProfile.isPostingPermitted());
228             url.setText(mProfile.getUrl());
229             useAuthentication.setChecked(mProfile.isAuthEnabled());
230             authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
231             userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
232             password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
233             profileThemeId = mProfile.getThemeId();
234         }
235         else {
236             profileName.setText("");
237             url.setText("https://");
238             postingPermitted.setChecked(true);
239             useAuthentication.setChecked(false);
240             authParams.setVisibility(View.GONE);
241             userName.setText("");
242             password.setText("");
243             profileThemeId = -1;
244         }
245
246         final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
247         final int profileColor = Colors.getPrimaryColorForHue(hue);
248
249         huePickerView.setBackgroundColor(profileColor);
250         huePickerView.setTag(profileThemeId);
251         huePickerView.setOnClickListener(v -> {
252             HueRingDialog d = new HueRingDialog(
253                     Objects.requireNonNull(ProfileDetailFragment.this.getContext()), hue);
254             d.show();
255             d.setColorSelectedListener(this);
256         });
257         return rootView;
258     }
259     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
260         view.setOnFocusChangeListener((v, hasFocus) -> {
261             if (hasFocus) layout.setError(null);
262         });
263         view.addTextChangedListener(new TextWatcher() {
264             @Override
265             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
266             }
267             @Override
268             public void onTextChanged(CharSequence s, int start, int before, int count) {
269                 layout.setError(null);
270             }
271             @Override
272             public void afterTextChanged(Editable s) {
273             }
274         });
275     }
276     private boolean checkValidity() {
277         boolean valid = true;
278
279         String val = String.valueOf(profileName.getText());
280         if (val.trim().isEmpty()) {
281             valid = false;
282             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
283         }
284
285         val = String.valueOf(url.getText());
286         if (val.trim().isEmpty()) {
287             valid = false;
288             urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
289         }
290         if (useAuthentication.isChecked()) {
291             val = String.valueOf(userName.getText());
292             if (val.trim().isEmpty()) {
293                 valid = false;
294                 userNameLayout
295                         .setError(getResources().getText(R.string.err_profile_user_name_empty));
296             }
297
298             val = String.valueOf(password.getText());
299             if (val.trim().isEmpty()) {
300                 valid = false;
301                 passwordLayout
302                         .setError(getResources().getText(R.string.err_profile_password_empty));
303             }
304         }
305
306         return valid;
307     }
308     @Override
309     public void onHueSelected(int hue) {
310         huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
311         huePickerView.setTag(hue);
312     }
313 }