]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
use the hue selector for profile color management
[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.getList().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         if (mProfile != null) {
200             profileName.setText(mProfile.getName());
201             postingPermitted.setChecked(mProfile.isPostingPermitted());
202             url.setText(mProfile.getUrl());
203             useAuthentication.setChecked(mProfile.isAuthEnabled());
204             authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
205             userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
206             password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
207
208             huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(
209                     (mProfile.getThemeId() == -1) ? Colors.DEFAULT_HUE_DEG
210                                                   : mProfile.getThemeId()));
211         }
212         else {
213             profileName.setText("");
214             url.setText("");
215             postingPermitted.setChecked(true);
216             useAuthentication.setChecked(false);
217             authParams.setVisibility(View.GONE);
218             userName.setText("");
219             password.setText("");
220             huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(Colors.DEFAULT_HUE_DEG));
221         }
222
223         int profileThemeId = (mProfile == null) ? -1 : mProfile.getThemeId();
224         final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
225         final int profileColor = Colors.getPrimaryColorForHue(hue);
226
227         huePickerView.setBackgroundColor(profileColor);
228         huePickerView.setOnClickListener(v -> {
229             HueRingDialog d = new HueRingDialog(
230                     Objects.requireNonNull(ProfileDetailFragment.this.getContext()), hue);
231             d.show();
232             d.setColorSelectedListener(this);
233         });
234         return rootView;
235     }
236     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
237         view.setOnFocusChangeListener((v, hasFocus) -> {
238             if (hasFocus) layout.setError(null);
239         });
240         view.addTextChangedListener(new TextWatcher() {
241             @Override
242             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
243             }
244             @Override
245             public void onTextChanged(CharSequence s, int start, int before, int count) {
246                 layout.setError(null);
247             }
248             @Override
249             public void afterTextChanged(Editable s) {
250             }
251         });
252     }
253     private boolean checkValidity() {
254         boolean valid = true;
255
256         String val = String.valueOf(profileName.getText());
257         if (val.trim().isEmpty()) {
258             valid = false;
259             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
260         }
261
262         val = String.valueOf(url.getText());
263         if (val.trim().isEmpty()) {
264             valid = false;
265             urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
266         }
267         if (useAuthentication.isChecked()) {
268             val = String.valueOf(userName.getText());
269             if (val.trim().isEmpty()) {
270                 valid = false;
271                 userNameLayout
272                         .setError(getResources().getText(R.string.err_profile_user_name_empty));
273             }
274
275             val = String.valueOf(password.getText());
276             if (val.trim().isEmpty()) {
277                 valid = false;
278                 passwordLayout
279                         .setError(getResources().getText(R.string.err_profile_password_empty));
280             }
281         }
282
283         return valid;
284     }
285     @Override
286     public void onHueSelected(int hue) {
287         huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
288         huePickerView.setTag(hue);
289     }
290 }