]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
whitespace and wrapping
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionItemHolder.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.activity;
19
20 import android.annotation.SuppressLint;
21 import android.os.Build;
22 import android.text.Editable;
23 import android.text.TextWatcher;
24 import android.text.method.DigitsKeyListener;
25 import android.view.View;
26 import android.view.inputmethod.EditorInfo;
27 import android.widget.AutoCompleteTextView;
28 import android.widget.FrameLayout;
29 import android.widget.LinearLayout;
30 import android.widget.TextView;
31
32 import androidx.annotation.NonNull;
33 import androidx.lifecycle.Observer;
34 import androidx.recyclerview.widget.RecyclerView;
35
36 import net.ktnx.mobileledger.R;
37 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
38 import net.ktnx.mobileledger.model.Data;
39 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
40 import net.ktnx.mobileledger.model.MobileLedgerProfile;
41 import net.ktnx.mobileledger.ui.AutoCompleteTextViewWithClear;
42 import net.ktnx.mobileledger.ui.DatePickerFragment;
43 import net.ktnx.mobileledger.utils.Logger;
44 import net.ktnx.mobileledger.utils.MLDB;
45 import net.ktnx.mobileledger.utils.Misc;
46
47 import java.text.DecimalFormatSymbols;
48 import java.util.Calendar;
49 import java.util.Date;
50 import java.util.GregorianCalendar;
51 import java.util.Locale;
52
53 class NewTransactionItemHolder extends RecyclerView.ViewHolder
54         implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
55     private final String decimalSeparator;
56     private final String decimalDot;
57     private NewTransactionModel.Item item;
58     private TextView tvDate;
59     private AutoCompleteTextView tvDescription;
60     private AutoCompleteTextView tvAccount;
61     private TextView tvAmount;
62     private LinearLayout lHead;
63     private LinearLayout lAccount;
64     private FrameLayout lPadding;
65     private MobileLedgerProfile mProfile;
66     private Date date;
67     private Observer<Date> dateObserver;
68     private Observer<String> descriptionObserver;
69     private Observer<String> hintObserver;
70     private Observer<Integer> focusedAccountObserver;
71     private Observer<Integer> accountCountObserver;
72     private Observer<Boolean> editableObserver;
73     private boolean inUpdate = false;
74     private boolean syncingData = false;
75     NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
76         super(itemView);
77         tvAccount = itemView.findViewById(R.id.account_row_acc_name);
78         tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
79         tvDate = itemView.findViewById(R.id.new_transaction_date);
80         tvDescription = itemView.findViewById(R.id.new_transaction_description);
81         lHead = itemView.findViewById(R.id.ntr_data);
82         lAccount = itemView.findViewById(R.id.ntr_account);
83         lPadding = itemView.findViewById(R.id.ntr_padding);
84
85         tvDescription.setNextFocusForwardId(View.NO_ID);
86         tvAccount.setNextFocusForwardId(View.NO_ID);
87         tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
88
89         tvDate.setOnClickListener(v -> pickTransactionDate());
90
91         mProfile = Data.profile.getValue();
92         if (mProfile == null)
93             throw new AssertionError();
94
95         View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
96             if (hasFocus) {
97                 boolean wasSyncing = syncingData;
98                 syncingData = true;
99                 try {
100                     final int pos = getAdapterPosition();
101                     adapter.updateFocusedItem(pos);
102                     if (v instanceof AutoCompleteTextViewWithClear) {
103                         adapter.noteFocusIsOnAccount(pos);
104                     }
105                     else {
106                         adapter.noteFocusIsOnAmount(pos);
107                     }
108                 }
109                 finally {
110                     syncingData = wasSyncing;
111                 }
112             }
113         };
114
115         tvDescription.setOnFocusChangeListener(focusMonitor);
116         tvAccount.setOnFocusChangeListener(focusMonitor);
117         tvAmount.setOnFocusChangeListener(focusMonitor);
118
119         MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
120                 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
121         MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
122                 "name", true, this, mProfile);
123
124         // FIXME: react on configuration (locale) changes
125         decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
126                                                               .getMonetaryDecimalSeparator());
127         decimalDot = ".";
128
129         final TextWatcher tw = new TextWatcher() {
130             @Override
131             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
132             }
133
134             @Override
135             public void onTextChanged(CharSequence s, int start, int before, int count) {
136             }
137
138             @Override
139             public void afterTextChanged(Editable s) {
140 //                debug("input", "text changed");
141                 if (inUpdate)
142                     return;
143
144                 Logger.debug("textWatcher", "calling syncData()");
145                 syncData();
146                 Logger.debug("textWatcher",
147                         "syncData() returned, checking if transaction is submittable");
148                 adapter.model.checkTransactionSubmittable(adapter);
149                 Logger.debug("textWatcher", "done");
150             }
151         };
152         final TextWatcher amountWatcher = new TextWatcher() {
153             @Override
154             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
155             }
156             @Override
157             public void onTextChanged(CharSequence s, int start, int before, int count) {
158
159             }
160             @Override
161             public void afterTextChanged(Editable s) {
162                 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
163                     // only one decimal separator is allowed
164                     // plus and minus are allowed only at the beginning
165                     String val = s.toString();
166                     if (val.isEmpty())
167                         tvAmount.setKeyListener(DigitsKeyListener.getInstance(
168                                 "0123456789+-" + decimalSeparator + decimalDot));
169                     else if (val.contains(decimalSeparator) || val.contains(decimalDot))
170                         tvAmount.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
171                     else
172                         tvAmount.setKeyListener(DigitsKeyListener.getInstance(
173                                 "0123456789" + decimalSeparator + decimalDot));
174
175                     syncData();
176                     adapter.model.checkTransactionSubmittable(adapter);
177                 }
178             }
179         };
180         tvDescription.addTextChangedListener(tw);
181         tvAccount.addTextChangedListener(tw);
182         tvAmount.addTextChangedListener(amountWatcher);
183
184         // FIXME: react on locale changes
185         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
186             tvAmount.setKeyListener(DigitsKeyListener.getInstance(Locale.getDefault(), true, true));
187         else
188             tvAmount.setKeyListener(
189                     DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
190
191         dateObserver = date -> {
192             if (syncingData)
193                 return;
194             syncingData = true;
195             try {
196                 tvDate.setText(item.getFormattedDate());
197             }
198             finally {
199                 syncingData = false;
200             }
201         };
202         descriptionObserver = description -> {
203             if (syncingData)
204                 return;
205             syncingData = true;
206             try {
207                 tvDescription.setText(description);
208             }
209             finally {
210                 syncingData = false;
211             }
212         };
213         hintObserver = hint -> {
214             if (syncingData)
215                 return;
216             syncingData = true;
217             try {
218                 if (hint == null)
219                     tvAmount.setHint(R.string.zero_amount);
220                 else
221                     tvAmount.setHint(hint);
222             }
223             finally {
224                 syncingData = false;
225             }
226         };
227         editableObserver = this::setEditable;
228         focusedAccountObserver = index -> {
229             if ((index != null) && index.equals(getAdapterPosition())) {
230                 switch (item.getType()) {
231                     case generalData:
232                         // bad idea - double pop-up, and not really necessary.
233                         // the user can tap the input to get the calendar
234                         //if (!tvDate.hasFocus()) tvDate.requestFocus();
235                         boolean focused = tvDescription.requestFocus();
236                         tvDescription.dismissDropDown();
237                         if (focused)
238                             Misc.showSoftKeyboard(
239                                     (NewTransactionActivity) tvDescription.getContext());
240                         break;
241                     case transactionRow:
242                         // do nothing if a row element already has the focus
243                         if (!itemView.hasFocus()) {
244                             if (item.focusIsOnAmount()) {
245                                 tvAmount.requestFocus();
246                             }
247                             else {
248                                 focused = tvAccount.requestFocus();
249                                 tvAccount.dismissDropDown();
250                                 if (focused)
251                                     Misc.showSoftKeyboard(
252                                             (NewTransactionActivity) tvAccount.getContext());
253                             }
254                         }
255
256                         break;
257                 }
258             }
259         };
260         accountCountObserver = count -> {
261             final int adapterPosition = getAdapterPosition();
262             final int layoutPosition = getLayoutPosition();
263             Logger.debug("holder",
264                     String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
265                             adapterPosition, layoutPosition, item.getType()
266                                                                  .toString()
267                                                                  .concat(item.getType() ==
268                                                                          NewTransactionModel.ItemType.transactionRow
269                                                                          ? String.format(Locale.US,
270                                                                          "'%s'=%s",
271                                                                          item.getAccount()
272                                                                              .getAccountName(),
273                                                                          item.getAccount()
274                                                                              .isAmountSet()
275                                                                          ? String.format(Locale.US,
276                                                                                  "%.2f",
277                                                                                  item.getAccount()
278                                                                                      .getAmount())
279                                                                          : "unset") : "")));
280             if (adapterPosition == count)
281                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
282             else
283                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
284         };
285     }
286     private void setEditable(Boolean editable) {
287         tvDate.setEnabled(editable);
288         tvDescription.setEnabled(editable);
289         tvAccount.setEnabled(editable);
290         tvAmount.setEnabled(editable);
291     }
292     private void beginUpdates() {
293         if (inUpdate)
294             throw new RuntimeException("Already in update mode");
295         inUpdate = true;
296     }
297     private void endUpdates() {
298         if (!inUpdate)
299             throw new RuntimeException("Not in update mode");
300         inUpdate = false;
301     }
302     /**
303      * syncData()
304      * <p>
305      * Stores the data from the UI elements into the model item
306      */
307     private void syncData() {
308         if (item == null)
309             return;
310
311         if (syncingData) {
312             Logger.debug("new-trans", "skipping syncData() loop");
313             return;
314         }
315
316         syncingData = true;
317
318         try {
319             switch (item.getType()) {
320                 case generalData:
321                     item.setDate(String.valueOf(tvDate.getText()));
322                     item.setDescription(String.valueOf(tvDescription.getText()));
323                     break;
324                 case transactionRow:
325                     item.getAccount()
326                         .setAccountName(String.valueOf(tvAccount.getText()));
327
328                     // TODO: handle multiple amounts
329                     String amount = String.valueOf(tvAmount.getText());
330                     amount = amount.trim();
331
332                     if (amount.isEmpty()) {
333                         item.getAccount()
334                             .resetAmount();
335                     }
336                     else {
337                         try {
338                             amount = amount.replace(decimalSeparator, decimalDot);
339                             item.getAccount()
340                                 .setAmount(Float.parseFloat(amount));
341                         }
342                         catch (NumberFormatException e) {
343                             Logger.debug("new-trans", String.format(
344                                     "assuming amount is not set due to number format exception. " +
345                                     "input was '%s'", amount));
346                             item.getAccount()
347                                 .resetAmount();
348                         }
349                     }
350
351                     break;
352                 case bottomFiller:
353                     throw new RuntimeException("Should not happen");
354             }
355         }
356         finally {
357             syncingData = false;
358         }
359     }
360     private void pickTransactionDate() {
361         DatePickerFragment picker = new DatePickerFragment();
362         picker.setFutureDates(mProfile.getFutureDates());
363         picker.setOnDatePickedListener(this);
364         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
365                 "datePicker");
366     }
367     /**
368      * setData
369      *
370      * @param item updates the UI elements with the data from the model item
371      */
372     @SuppressLint("DefaultLocale")
373     public void setData(NewTransactionModel.Item item) {
374         beginUpdates();
375         try {
376             if (this.item != null && !this.item.equals(item)) {
377                 this.item.stopObservingDate(dateObserver);
378                 this.item.stopObservingDescription(descriptionObserver);
379                 this.item.stopObservingAmountHint(hintObserver);
380                 this.item.stopObservingEditableFlag(editableObserver);
381                 this.item.getModel()
382                          .stopObservingFocusedItem(focusedAccountObserver);
383                 this.item.getModel()
384                          .stopObservingAccountCount(accountCountObserver);
385
386                 this.item = null;
387             }
388
389             switch (item.getType()) {
390                 case generalData:
391                     tvDate.setText(item.getFormattedDate());
392                     tvDescription.setText(item.getDescription());
393                     lHead.setVisibility(View.VISIBLE);
394                     lAccount.setVisibility(View.GONE);
395                     lPadding.setVisibility(View.GONE);
396                     setEditable(true);
397                     break;
398                 case transactionRow:
399                     LedgerTransactionAccount acc = item.getAccount();
400                     tvAccount.setText(acc.getAccountName());
401                     if (acc.isAmountSet()) {
402                         tvAmount.setText(String.format("%1.2f", acc.getAmount()));
403                     }
404                     else {
405                         tvAmount.setText("");
406 //                        tvAmount.setHint(R.string.zero_amount);
407                     }
408                     tvAmount.setHint(item.getAmountHint());
409                     lHead.setVisibility(View.GONE);
410                     lAccount.setVisibility(View.VISIBLE);
411                     lPadding.setVisibility(View.GONE);
412                     setEditable(true);
413                     break;
414                 case bottomFiller:
415                     lHead.setVisibility(View.GONE);
416                     lAccount.setVisibility(View.GONE);
417                     lPadding.setVisibility(View.VISIBLE);
418                     setEditable(false);
419                     break;
420             }
421
422             if (this.item == null) { // was null or has changed
423                 this.item = item;
424                 final NewTransactionActivity activity =
425                         (NewTransactionActivity) tvDescription.getContext();
426                 item.observeDate(activity, dateObserver);
427                 item.observeDescription(activity, descriptionObserver);
428                 item.observeAmountHint(activity, hintObserver);
429                 item.observeEditableFlag(activity, editableObserver);
430                 item.getModel()
431                     .observeFocusedItem(activity, focusedAccountObserver);
432                 item.getModel()
433                     .observeAccountCount(activity, accountCountObserver);
434             }
435         }
436         finally {
437             endUpdates();
438         }
439     }
440     @Override
441     public void onDatePicked(int year, int month, int day) {
442         final Calendar c = GregorianCalendar.getInstance();
443         c.set(year, month, day);
444         item.setDate(c.getTime());
445         boolean focused = tvDescription.requestFocus();
446         if (focused)
447             Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
448
449     }
450     @Override
451     public void descriptionSelected(String description) {
452         tvAccount.setText(description);
453         tvAmount.requestFocus(View.FOCUS_FORWARD);
454     }
455 }