]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
81487af661a1f4b7dcc9c9539f1991755c32eba8
[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             if (getAdapterPosition() == count) tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
175             else tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
176         };
177     }
178     private void beginUpdates() {
179         if (inUpdate) throw new RuntimeException("Already in update mode");
180         inUpdate = true;
181     }
182     private void endUpdates() {
183         if (!inUpdate) throw new RuntimeException("Not in update mode");
184         inUpdate = false;
185     }
186     /**
187      * syncData()
188      * <p>
189      * Stores the data from the UI elements into the model item
190      */
191     private void syncData() {
192         if (item == null) return;
193
194         if (syncingData) {
195             Logger.debug("new-trans", "skipping syncData() loop");
196             return;
197         }
198
199         syncingData = true;
200
201         try {
202             switch (item.getType()) {
203                 case generalData:
204                     item.setDate(String.valueOf(tvDate.getText()));
205                     item.setDescription(String.valueOf(tvDescription.getText()));
206                     break;
207                 case transactionRow:
208                     item.getAccount()
209                         .setAccountName(String.valueOf(tvAccount.getText()));
210
211                     // TODO: handle multiple amounts
212                     String amount = String.valueOf(tvAmount.getText());
213                     amount = amount.trim();
214
215                     if (!amount.isEmpty()) item.getAccount()
216                                                .setAmount(Float.parseFloat(amount));
217                     else item.getAccount()
218                              .resetAmount();
219
220                     break;
221                 case bottomFiller:
222                     throw new RuntimeException("Should not happen");
223             }
224         }
225         finally {
226             syncingData = false;
227         }
228     }
229     private void pickTransactionDate() {
230         DatePickerFragment picker = new DatePickerFragment();
231         picker.setOnDatePickedListener(this);
232         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
233                 "datePicker");
234     }
235     /**
236      * setData
237      *
238      * @param item updates the UI elements with the data from the model item
239      */
240     public void setData(NewTransactionModel.Item item) {
241         beginUpdates();
242         try {
243             if (this.item != null && !this.item.equals(item)) {
244                 this.item.stopObservingDate(dateObserver);
245                 this.item.stopObservingDescription(descriptionObserver);
246                 this.item.stopObservingAmountHint(hintObserver);
247                 this.item.getModel()
248                          .stopObservingFocusedItem(focusedAccountObserver);
249                 this.item.getModel()
250                          .stopObservingAccountCount(accountCountObserver);
251
252                 this.item = null;
253             }
254
255             switch (item.getType()) {
256                 case generalData:
257                     tvDate.setText(item.getFormattedDate());
258                     tvDescription.setText(item.getDescription());
259                     lHead.setVisibility(View.VISIBLE);
260                     lAccount.setVisibility(View.GONE);
261                     lPadding.setVisibility(View.GONE);
262                     break;
263                 case transactionRow:
264                     LedgerTransactionAccount acc = item.getAccount();
265                     tvAccount.setText(acc.getAccountName());
266                     tvAmount.setText(
267                             acc.isAmountSet() ? String.format(Locale.US, "%1.2f", acc.getAmount())
268                                               : "");
269                     lHead.setVisibility(View.GONE);
270                     lAccount.setVisibility(View.VISIBLE);
271                     lPadding.setVisibility(View.GONE);
272                     break;
273                 case bottomFiller:
274                     lHead.setVisibility(View.GONE);
275                     lAccount.setVisibility(View.GONE);
276                     lPadding.setVisibility(View.VISIBLE);
277                     break;
278             }
279
280             if (this.item == null) { // was null or has changed
281                 this.item = item;
282                 final NewTransactionActivity activity =
283                         (NewTransactionActivity) tvDescription.getContext();
284                 item.observeDate(activity, dateObserver);
285                 item.observeDescription(activity, descriptionObserver);
286                 item.observeAmountHint(activity, hintObserver);
287                 item.getModel()
288                     .observeFocusedItem(activity, focusedAccountObserver);
289                 item.getModel()
290                     .observeAccountCount(activity, accountCountObserver);
291             }
292         }
293         finally {
294             endUpdates();
295         }
296     }
297     @Override
298     public void onDatePicked(int year, int month, int day) {
299         final Calendar c = GregorianCalendar.getInstance();
300         c.set(year, month, day);
301         item.setDate(c.getTime());
302         boolean focused = tvDescription.requestFocus();
303         if (focused) Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
304
305     }
306     @Override
307     public void descriptionSelected(String description) {
308         tvAccount.setText(description);
309         tvAmount.requestFocus(View.FOCUS_FORWARD);
310     }
311 }