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