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