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