]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
rework new transaction activity with a RecyclerView
[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.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.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
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         MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
88                 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
89         MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
90                 "name", true, this, mProfile);
91
92         final TextWatcher tw = new TextWatcher() {
93             @Override
94             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
95             }
96
97             @Override
98             public void onTextChanged(CharSequence s, int start, int before, int count) {
99             }
100
101             @Override
102             public void afterTextChanged(Editable s) {
103 //                debug("input", "text changed");
104                 if (inUpdate) return;
105
106                 Logger.debug("textWatcher", "calling syncData()");
107                 syncData();
108                 Logger.debug("textWatcher",
109                         "syncData() returned, checking if transaction is submittable");
110                 adapter.model.checkTransactionSubmittable(adapter);
111                 Logger.debug("textWatcher", "done");
112             }
113         };
114         tvDescription.addTextChangedListener(tw);
115         tvAccount.addTextChangedListener(tw);
116         tvAmount.addTextChangedListener(tw);
117
118         dateObserver = date -> {
119             if (syncingData) return;
120             tvDate.setText(item.getFormattedDate());
121         };
122         descriptionObserver = description -> {
123             if (syncingData) return;
124             tvDescription.setText(description);
125         };
126         hintObserver = hint -> {
127             if (syncingData) return;
128             tvAmount.setHint(hint);
129         };
130         focusedAccountObserver = index -> {
131             if ((index != null) && index.equals(getAdapterPosition())) {
132                 switch (item.getType()) {
133                     case generalData:
134                         tvDate.requestFocus();
135                         break;
136                     case transactionRow:
137                         tvAccount.requestFocus();
138                         tvAccount.dismissDropDown();
139                         tvAccount.selectAll();
140                         break;
141                 }
142             }
143         };
144         accountCountObserver = count -> {
145             if (getAdapterPosition() == count) tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
146             else tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
147         };
148     }
149     private void beginUpdates() {
150         if (inUpdate) throw new RuntimeException("Already in update mode");
151         inUpdate = true;
152     }
153     private void endUpdates() {
154         if (!inUpdate) throw new RuntimeException("Not in update mode");
155         inUpdate = false;
156     }
157     /**
158      * syncData()
159      * <p>
160      * Stores the data from the UI elements into the model item
161      */
162     private void syncData() {
163         if (item == null) return;
164
165         if (syncingData) {
166             Logger.debug("new-trans", "skipping syncData() loop");
167             return;
168         }
169
170         syncingData = true;
171
172         try {
173             switch (item.getType()) {
174                 case generalData:
175                     item.setDate(String.valueOf(tvDate.getText()));
176                     item.setDescription(String.valueOf(tvDescription.getText()));
177                     break;
178                 case transactionRow:
179                     item.getAccount()
180                         .setAccountName(String.valueOf(tvAccount.getText()));
181
182                     // TODO: handle multiple amounts
183                     String amount = String.valueOf(tvAmount.getText());
184                     amount = amount.trim();
185
186                     if (!amount.isEmpty()) item.getAccount()
187                                                .setAmount(Float.parseFloat(amount));
188                     else item.getAccount()
189                              .resetAmount();
190
191                     break;
192                 case bottomFiller:
193                     throw new RuntimeException("Should not happen");
194             }
195         }
196         finally {
197             syncingData = false;
198         }
199     }
200     private void pickTransactionDate() {
201         DatePickerFragment picker = new DatePickerFragment();
202         picker.setOnDatePickedListener(this);
203         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
204                 "datePicker");
205     }
206     /**
207      * setData
208      *
209      * @param item updates the UI elements with the data from the model item
210      */
211     public void setData(NewTransactionModel.Item item) {
212         beginUpdates();
213         try {
214             if (this.item != null && !this.item.equals(item)) {
215                 this.item.stopObservingDate(dateObserver);
216                 this.item.stopObservingDescription(descriptionObserver);
217                 this.item.stopObservingAmountHint(hintObserver);
218                 this.item.getModel()
219                          .stopObservingFocusedItem(focusedAccountObserver);
220                 this.item.getModel()
221                          .stopObservingAccountCount(accountCountObserver);
222
223                 this.item = null;
224             }
225
226             switch (item.getType()) {
227                 case generalData:
228                     tvDate.setText(item.getFormattedDate());
229                     tvDescription.setText(item.getDescription());
230                     lHead.setVisibility(View.VISIBLE);
231                     lAccount.setVisibility(View.GONE);
232                     lPadding.setVisibility(View.GONE);
233                     break;
234                 case transactionRow:
235                     LedgerTransactionAccount acc = item.getAccount();
236                     tvAccount.setText(acc.getAccountName());
237                     tvAmount.setText(
238                             acc.isAmountSet() ? String.format(Locale.US, "%1.2f", acc.getAmount())
239                                               : "");
240                     lHead.setVisibility(View.GONE);
241                     lAccount.setVisibility(View.VISIBLE);
242                     lPadding.setVisibility(View.GONE);
243                     break;
244                 case bottomFiller:
245                     lHead.setVisibility(View.GONE);
246                     lAccount.setVisibility(View.GONE);
247                     lPadding.setVisibility(View.VISIBLE);
248                     break;
249             }
250
251             if (this.item == null) { // was null or has changed
252                 this.item = item;
253                 final NewTransactionActivity activity =
254                         (NewTransactionActivity) tvDescription.getContext();
255                 item.observeDate(activity, dateObserver);
256                 item.observeDescription(activity, descriptionObserver);
257                 item.observeAmountHint(activity, hintObserver);
258                 item.getModel()
259                     .observeFocusedItem(activity, focusedAccountObserver);
260                 item.getModel()
261                     .observeAccountCount(activity, accountCountObserver);
262             }
263         }
264         finally {
265             endUpdates();
266         }
267     }
268     @Override
269     public void onDatePicked(int year, int month, int day) {
270         final Calendar c = GregorianCalendar.getInstance();
271         c.set(year, month, day);
272         item.setDate(c.getTime());
273         boolean tookFocus = tvDescription.requestFocus();
274         if (tookFocus) {
275             // make the keyboard appear
276             InputMethodManager imm = (InputMethodManager) tvDate.getContext()
277                                                                 .getSystemService(
278                                                                         Context.INPUT_METHOD_SERVICE);
279             imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
280         }
281     }
282     @Override
283     public void descriptionSelected(String description) {
284         tvAccount.setText(description);
285         tvAmount.requestFocus(View.FOCUS_FORWARD);
286     }
287 }