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