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