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