]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
f83eec8ae036b859f5de9f3b57cca88b922e9329
[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((NewTransactionActivity) tvAccount.getContext());
252                             }
253                         }
254
255                         break;
256                 }
257             }
258         };
259         accountCountObserver = count -> {
260             final int adapterPosition = getAdapterPosition();
261             final int layoutPosition = getLayoutPosition();
262             Logger.debug("holder",
263                     String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
264                             adapterPosition, layoutPosition, item.getType()
265                                                                  .toString()
266                                                                  .concat(item.getType() ==
267                                                                          NewTransactionModel.ItemType.transactionRow
268                                                                          ? String.format(Locale.US,
269                                                                          "'%s'=%s",
270                                                                          item.getAccount()
271                                                                              .getAccountName(),
272                                                                          item.getAccount()
273                                                                              .isAmountSet()
274                                                                          ? String.format(Locale.US,
275                                                                                  "%.2f",
276                                                                                  item.getAccount()
277                                                                                      .getAmount())
278                                                                          : "unset") : "")));
279             if (adapterPosition == count)
280                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
281             else
282                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
283         };
284     }
285     private void setEditable(Boolean editable) {
286         tvDate.setEnabled(editable);
287         tvDescription.setEnabled(editable);
288         tvAccount.setEnabled(editable);
289         tvAmount.setEnabled(editable);
290     }
291     private void beginUpdates() {
292         if (inUpdate)
293             throw new RuntimeException("Already in update mode");
294         inUpdate = true;
295     }
296     private void endUpdates() {
297         if (!inUpdate)
298             throw new RuntimeException("Not in update mode");
299         inUpdate = false;
300     }
301     /**
302      * syncData()
303      * <p>
304      * Stores the data from the UI elements into the model item
305      */
306     private void syncData() {
307         if (item == null)
308             return;
309
310         if (syncingData) {
311             Logger.debug("new-trans", "skipping syncData() loop");
312             return;
313         }
314
315         syncingData = true;
316
317         try {
318             switch (item.getType()) {
319                 case generalData:
320                     item.setDate(String.valueOf(tvDate.getText()));
321                     item.setDescription(String.valueOf(tvDescription.getText()));
322                     break;
323                 case transactionRow:
324                     item.getAccount()
325                         .setAccountName(String.valueOf(tvAccount.getText()));
326
327                     // TODO: handle multiple amounts
328                     String amount = String.valueOf(tvAmount.getText());
329                     amount = amount.trim();
330
331                     if (amount.isEmpty()) {
332                         item.getAccount()
333                             .resetAmount();
334                     }
335                     else {
336                         try {
337                             amount = amount.replace(decimalSeparator, decimalDot);
338                             item.getAccount()
339                                 .setAmount(Float.parseFloat(amount));
340                         }
341                         catch (NumberFormatException e) {
342                             Logger.debug("new-trans", String.format(
343                                     "assuming amount is not set due to number format exception. " +
344                                     "input was '%s'", amount));
345                             item.getAccount()
346                                 .resetAmount();
347                         }
348                     }
349
350                     break;
351                 case bottomFiller:
352                     throw new RuntimeException("Should not happen");
353             }
354         }
355         finally {
356             syncingData = false;
357         }
358     }
359     private void pickTransactionDate() {
360         DatePickerFragment picker = new DatePickerFragment();
361         picker.setOnDatePickedListener(this);
362         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
363                 "datePicker");
364     }
365     /**
366      * setData
367      *
368      * @param item updates the UI elements with the data from the model item
369      */
370     @SuppressLint("DefaultLocale")
371     public void setData(NewTransactionModel.Item item) {
372         beginUpdates();
373         try {
374             if (this.item != null && !this.item.equals(item)) {
375                 this.item.stopObservingDate(dateObserver);
376                 this.item.stopObservingDescription(descriptionObserver);
377                 this.item.stopObservingAmountHint(hintObserver);
378                 this.item.stopObservingEditableFlag(editableObserver);
379                 this.item.getModel()
380                          .stopObservingFocusedItem(focusedAccountObserver);
381                 this.item.getModel()
382                          .stopObservingAccountCount(accountCountObserver);
383
384                 this.item = null;
385             }
386
387             switch (item.getType()) {
388                 case generalData:
389                     tvDate.setText(item.getFormattedDate());
390                     tvDescription.setText(item.getDescription());
391                     lHead.setVisibility(View.VISIBLE);
392                     lAccount.setVisibility(View.GONE);
393                     lPadding.setVisibility(View.GONE);
394                     setEditable(true);
395                     break;
396                 case transactionRow:
397                     LedgerTransactionAccount acc = item.getAccount();
398                     tvAccount.setText(acc.getAccountName());
399                     if (acc.isAmountSet()) {
400                         tvAmount.setText(String.format("%1.2f", acc.getAmount()));
401                     }
402                     else {
403                         tvAmount.setText("");
404 //                        tvAmount.setHint(R.string.zero_amount);
405                     }
406                     tvAmount.setHint(item.getAmountHint());
407                     lHead.setVisibility(View.GONE);
408                     lAccount.setVisibility(View.VISIBLE);
409                     lPadding.setVisibility(View.GONE);
410                     setEditable(true);
411                     break;
412                 case bottomFiller:
413                     lHead.setVisibility(View.GONE);
414                     lAccount.setVisibility(View.GONE);
415                     lPadding.setVisibility(View.VISIBLE);
416                     setEditable(false);
417                     break;
418             }
419
420             if (this.item == null) { // was null or has changed
421                 this.item = item;
422                 final NewTransactionActivity activity =
423                         (NewTransactionActivity) tvDescription.getContext();
424                 item.observeDate(activity, dateObserver);
425                 item.observeDescription(activity, descriptionObserver);
426                 item.observeAmountHint(activity, hintObserver);
427                 item.observeEditableFlag(activity, editableObserver);
428                 item.getModel()
429                     .observeFocusedItem(activity, focusedAccountObserver);
430                 item.getModel()
431                     .observeAccountCount(activity, accountCountObserver);
432             }
433         }
434         finally {
435             endUpdates();
436         }
437     }
438     @Override
439     public void onDatePicked(int year, int month, int day) {
440         final Calendar c = GregorianCalendar.getInstance();
441         c.set(year, month, day);
442         item.setDate(c.getTime());
443         boolean focused = tvDescription.requestFocus();
444         if (focused)
445             Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
446
447     }
448     @Override
449     public void descriptionSelected(String description) {
450         tvAccount.setText(description);
451         tvAmount.requestFocus(View.FOCUS_FORWARD);
452     }
453 }