]> git.ktnx.net Git - mobile-ledger-staging.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
auto select new transaction description/amounts upon focus
[mobile-ledger-staging.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.content.Context;
21 import android.text.Editable;
22 import android.text.TextWatcher;
23 import android.view.View;
24 import android.view.inputmethod.EditorInfo;
25 import android.view.inputmethod.InputMethodManager;
26 import android.widget.AutoCompleteTextView;
27 import android.widget.FrameLayout;
28 import android.widget.LinearLayout;
29 import android.widget.TextView;
30
31 import androidx.annotation.NonNull;
32 import androidx.constraintlayout.widget.ConstraintLayout;
33 import androidx.lifecycle.Observer;
34 import androidx.recyclerview.widget.RecyclerView;
35
36 import net.ktnx.mobileledger.R;
37 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
38 import net.ktnx.mobileledger.model.Data;
39 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
40 import net.ktnx.mobileledger.model.MobileLedgerProfile;
41 import net.ktnx.mobileledger.ui.DatePickerFragment;
42 import net.ktnx.mobileledger.utils.Logger;
43 import net.ktnx.mobileledger.utils.MLDB;
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 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         focusedAccountObserver = index -> {
153             if ((index != null) && index.equals(getAdapterPosition())) {
154                 switch (item.getType()) {
155                     case generalData:
156                         tvDate.requestFocus();
157                         break;
158                     case transactionRow:
159                         tvAccount.requestFocus();
160                         tvAccount.dismissDropDown();
161                         break;
162                 }
163             }
164         };
165         accountCountObserver = count -> {
166             if (getAdapterPosition() == count) tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
167             else tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
168         };
169     }
170     private void beginUpdates() {
171         if (inUpdate) throw new RuntimeException("Already in update mode");
172         inUpdate = true;
173     }
174     private void endUpdates() {
175         if (!inUpdate) throw new RuntimeException("Not in update mode");
176         inUpdate = false;
177     }
178     /**
179      * syncData()
180      * <p>
181      * Stores the data from the UI elements into the model item
182      */
183     private void syncData() {
184         if (item == null) return;
185
186         if (syncingData) {
187             Logger.debug("new-trans", "skipping syncData() loop");
188             return;
189         }
190
191         syncingData = true;
192
193         try {
194             switch (item.getType()) {
195                 case generalData:
196                     item.setDate(String.valueOf(tvDate.getText()));
197                     item.setDescription(String.valueOf(tvDescription.getText()));
198                     break;
199                 case transactionRow:
200                     item.getAccount()
201                         .setAccountName(String.valueOf(tvAccount.getText()));
202
203                     // TODO: handle multiple amounts
204                     String amount = String.valueOf(tvAmount.getText());
205                     amount = amount.trim();
206
207                     if (!amount.isEmpty()) item.getAccount()
208                                                .setAmount(Float.parseFloat(amount));
209                     else item.getAccount()
210                              .resetAmount();
211
212                     break;
213                 case bottomFiller:
214                     throw new RuntimeException("Should not happen");
215             }
216         }
217         finally {
218             syncingData = false;
219         }
220     }
221     private void pickTransactionDate() {
222         DatePickerFragment picker = new DatePickerFragment();
223         picker.setOnDatePickedListener(this);
224         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
225                 "datePicker");
226     }
227     /**
228      * setData
229      *
230      * @param item updates the UI elements with the data from the model item
231      */
232     public void setData(NewTransactionModel.Item item) {
233         beginUpdates();
234         try {
235             if (this.item != null && !this.item.equals(item)) {
236                 this.item.stopObservingDate(dateObserver);
237                 this.item.stopObservingDescription(descriptionObserver);
238                 this.item.stopObservingAmountHint(hintObserver);
239                 this.item.getModel()
240                          .stopObservingFocusedItem(focusedAccountObserver);
241                 this.item.getModel()
242                          .stopObservingAccountCount(accountCountObserver);
243
244                 this.item = null;
245             }
246
247             switch (item.getType()) {
248                 case generalData:
249                     tvDate.setText(item.getFormattedDate());
250                     tvDescription.setText(item.getDescription());
251                     lHead.setVisibility(View.VISIBLE);
252                     lAccount.setVisibility(View.GONE);
253                     lPadding.setVisibility(View.GONE);
254                     break;
255                 case transactionRow:
256                     LedgerTransactionAccount acc = item.getAccount();
257                     tvAccount.setText(acc.getAccountName());
258                     tvAmount.setText(
259                             acc.isAmountSet() ? String.format(Locale.US, "%1.2f", acc.getAmount())
260                                               : "");
261                     lHead.setVisibility(View.GONE);
262                     lAccount.setVisibility(View.VISIBLE);
263                     lPadding.setVisibility(View.GONE);
264                     break;
265                 case bottomFiller:
266                     lHead.setVisibility(View.GONE);
267                     lAccount.setVisibility(View.GONE);
268                     lPadding.setVisibility(View.VISIBLE);
269                     break;
270             }
271
272             if (this.item == null) { // was null or has changed
273                 this.item = item;
274                 final NewTransactionActivity activity =
275                         (NewTransactionActivity) tvDescription.getContext();
276                 item.observeDate(activity, dateObserver);
277                 item.observeDescription(activity, descriptionObserver);
278                 item.observeAmountHint(activity, hintObserver);
279                 item.getModel()
280                     .observeFocusedItem(activity, focusedAccountObserver);
281                 item.getModel()
282                     .observeAccountCount(activity, accountCountObserver);
283             }
284         }
285         finally {
286             endUpdates();
287         }
288     }
289     @Override
290     public void onDatePicked(int year, int month, int day) {
291         final Calendar c = GregorianCalendar.getInstance();
292         c.set(year, month, day);
293         item.setDate(c.getTime());
294         boolean tookFocus = tvDescription.requestFocus();
295         if (tookFocus) {
296             // make the keyboard appear
297             InputMethodManager imm = (InputMethodManager) tvDate.getContext()
298                                                                 .getSystemService(
299                                                                         Context.INPUT_METHOD_SERVICE);
300             imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
301         }
302     }
303     @Override
304     public void descriptionSelected(String description) {
305         tvAccount.setText(description);
306         tvAmount.requestFocus(View.FOCUS_FORWARD);
307     }
308 }