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