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