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