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