]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionModel.java
move high-level login out of the new transaction model to the adapter
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionModel.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 androidx.annotation.NonNull;
21 import androidx.lifecycle.LifecycleOwner;
22 import androidx.lifecycle.LiveData;
23 import androidx.lifecycle.MutableLiveData;
24 import androidx.lifecycle.Observer;
25 import androidx.lifecycle.ViewModel;
26
27 import net.ktnx.mobileledger.model.Currency;
28 import net.ktnx.mobileledger.model.Data;
29 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
30 import net.ktnx.mobileledger.model.MobileLedgerProfile;
31
32 import org.jetbrains.annotations.NotNull;
33
34 import java.util.ArrayList;
35 import java.util.Calendar;
36 import java.util.Collections;
37 import java.util.Date;
38 import java.util.GregorianCalendar;
39 import java.util.Locale;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42
43 public class NewTransactionModel extends ViewModel {
44     private static final Pattern reYMD =
45             Pattern.compile("^\\s*(\\d+)\\d*/\\s*(\\d+)\\s*/\\s*(\\d+)\\s*$");
46     private static final Pattern reMD = Pattern.compile("^\\s*(\\d+)\\s*/\\s*(\\d+)\\s*$");
47     private static final Pattern reD = Pattern.compile("\\s*(\\d+)\\s*$");
48     final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
49     final ArrayList<Item> items = new ArrayList<>();
50     final MutableLiveData<Boolean> isSubmittable = new MutableLiveData<>(false);
51     private final Item header = new Item(this, null, "");
52     private final Item trailer = new Item(this);
53     private final MutableLiveData<Integer> focusedItem = new MutableLiveData<>(0);
54     private final MutableLiveData<Integer> accountCount = new MutableLiveData<>(0);
55     private final MutableLiveData<Boolean> simulateSave = new MutableLiveData<>(false);
56     private boolean observingDataProfile;
57     private Observer<MobileLedgerProfile> profileObserver =
58             profile -> showCurrency.postValue(profile.getShowCommodityByDefault());
59     void observeDataProfile(LifecycleOwner activity) {
60         if (!observingDataProfile)
61             Data.profile.observe(activity, profileObserver);
62         observingDataProfile = true;
63     }
64     boolean getSimulateSave() {
65         return simulateSave.getValue();
66     }
67     public void setSimulateSave(boolean simulateSave) {
68         this.simulateSave.setValue(simulateSave);
69     }
70     void toggleSimulateSave() {
71         simulateSave.setValue(!simulateSave.getValue());
72     }
73     void observeSimulateSave(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
74                              @NonNull androidx.lifecycle.Observer<? super Boolean> observer) {
75         this.simulateSave.observe(owner, observer);
76     }
77     int getAccountCount() {
78         return items.size();
79     }
80     public Date getDate() {
81         return header.date.getValue();
82     }
83     public String getDescription() {
84         return header.description.getValue();
85     }
86     LiveData<Boolean> isSubmittable() {
87         return this.isSubmittable;
88     }
89     void reset() {
90         header.date.setValue(null);
91         header.description.setValue(null);
92         items.clear();
93         items.add(new Item(this, new LedgerTransactionAccount("")));
94         items.add(new Item(this, new LedgerTransactionAccount("")));
95         focusedItem.setValue(0);
96     }
97     void observeFocusedItem(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
98                             @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
99         this.focusedItem.observe(owner, observer);
100     }
101     void stopObservingFocusedItem(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
102         this.focusedItem.removeObserver(observer);
103     }
104     void observeAccountCount(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
105                              @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
106         this.accountCount.observe(owner, observer);
107     }
108     void stopObservingAccountCount(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
109         this.accountCount.removeObserver(observer);
110     }
111     int getFocusedItem() { return focusedItem.getValue(); }
112     void setFocusedItem(int position) {
113         focusedItem.setValue(position);
114     }
115     int addAccount(LedgerTransactionAccount acc) {
116         items.add(new Item(this, acc));
117         accountCount.setValue(getAccountCount());
118         return items.size();
119     }
120     boolean accountsInInitialState() {
121         for (Item item : items) {
122             LedgerTransactionAccount acc = item.getAccount();
123             if (acc.isAmountSet())
124                 return false;
125             if (!acc.getAccountName()
126                     .trim()
127                     .isEmpty())
128                 return false;
129         }
130
131         return true;
132     }
133     LedgerTransactionAccount getAccount(int index) {
134         return items.get(index)
135                     .getAccount();
136     }
137     Item getItem(int index) {
138         if (index == 0) {
139             return header;
140         }
141
142         if (index <= items.size())
143             return items.get(index - 1);
144
145         return trailer;
146     }
147     void removeRow(Item item, NewTransactionItemsAdapter adapter) {
148         int pos = items.indexOf(item);
149         items.remove(pos);
150         if (adapter != null) {
151             adapter.notifyItemRemoved(pos + 1);
152             sendCountNotifications();
153         }
154     }
155     void removeItem(int pos) {
156         items.remove(pos);
157         accountCount.setValue(getAccountCount());
158     }
159     void sendCountNotifications() {
160         accountCount.setValue(getAccountCount());
161     }
162     public void sendFocusedNotification() {
163         focusedItem.setValue(focusedItem.getValue());
164     }
165     void updateFocusedItem(int position) {
166         focusedItem.setValue(position);
167     }
168     void noteFocusChanged(int position, FocusedElement element) {
169         getItem(position).setFocusedElement(element);
170     }
171     void swapItems(int one, int two) {
172         Collections.swap(items, one - 1, two - 1);
173     }
174     void toggleComment(int position) {
175         final MutableLiveData<Boolean> commentVisible = getItem(position).commentVisible;
176         commentVisible.postValue(!commentVisible.getValue());
177     }
178     void moveItemLast(int index) {
179         /*   0
180              1   <-- index
181              2
182              3   <-- desired position
183          */
184         int itemCount = items.size();
185
186         if (index < itemCount - 1) {
187             Item acc = items.remove(index);
188             items.add(itemCount - 1, acc);
189         }
190     }
191     void toggleCurrencyVisible() {
192         showCurrency.setValue(!showCurrency.getValue());
193     }
194     enum ItemType {generalData, transactionRow, bottomFiller}
195
196     enum FocusedElement {Account, Comment, Amount}
197
198
199     //==========================================================================================
200
201
202     static class Item {
203         private ItemType type;
204         private MutableLiveData<Date> date = new MutableLiveData<>();
205         private MutableLiveData<String> description = new MutableLiveData<>();
206         private LedgerTransactionAccount account;
207         private MutableLiveData<String> amountHint = new MutableLiveData<>(null);
208         private NewTransactionModel model;
209         private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
210         private FocusedElement focusedElement = FocusedElement.Account;
211         private MutableLiveData<String> comment = new MutableLiveData<>(null);
212         private MutableLiveData<Boolean> commentVisible = new MutableLiveData<>(false);
213         private MutableLiveData<Currency> currency = new MutableLiveData<>(null);
214         private boolean amountHintIsSet = false;
215         Item(NewTransactionModel model) {
216             this.model = model;
217             type = ItemType.bottomFiller;
218             editable.setValue(false);
219         }
220         Item(NewTransactionModel model, Date date, String description) {
221             this.model = model;
222             this.type = ItemType.generalData;
223             this.date.setValue(date);
224             this.description.setValue(description);
225             this.editable.setValue(true);
226         }
227         Item(NewTransactionModel model, LedgerTransactionAccount account) {
228             this.model = model;
229             this.type = ItemType.transactionRow;
230             this.account = account;
231             String currName = account.getCurrency();
232             Currency curr = null;
233             if ((currName != null) && !currName.isEmpty())
234                 curr = Currency.loadByName(currName);
235             this.currency.setValue(curr);
236             this.editable.setValue(true);
237         }
238         FocusedElement getFocusedElement() {
239             return focusedElement;
240         }
241         void setFocusedElement(FocusedElement focusedElement) {
242             this.focusedElement = focusedElement;
243         }
244         public NewTransactionModel getModel() {
245             return model;
246         }
247         void setEditable(boolean editable) {
248             ensureType(ItemType.generalData, ItemType.transactionRow);
249             this.editable.setValue(editable);
250         }
251         private void ensureType(ItemType type1, ItemType type2) {
252             if ((type != type1) && (type != type2)) {
253                 throw new RuntimeException(
254                         String.format("Actual type (%s) differs from wanted (%s or %s)", type,
255                                 type1, type2));
256             }
257         }
258         String getAmountHint() {
259             ensureType(ItemType.transactionRow);
260             return amountHint.getValue();
261         }
262         void setAmountHint(String amountHint) {
263             ensureType(ItemType.transactionRow);
264
265             // avoid unnecessary triggers
266             if (amountHint == null) {
267                 if (this.amountHint.getValue() == null)
268                     return;
269                 amountHintIsSet = false;
270             }
271             else {
272                 if (amountHint.equals(this.amountHint.getValue()))
273                     return;
274                 amountHintIsSet = true;
275             }
276
277             this.amountHint.setValue(amountHint);
278         }
279         void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
280                                @NonNull androidx.lifecycle.Observer<? super String> observer) {
281             this.amountHint.observe(owner, observer);
282         }
283         void stopObservingAmountHint(
284                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
285             this.amountHint.removeObserver(observer);
286         }
287         ItemType getType() {
288             return type;
289         }
290         void ensureType(ItemType wantedType) {
291             if (type != wantedType) {
292                 throw new RuntimeException(
293                         String.format("Actual type (%s) differs from wanted (%s)", type,
294                                 wantedType));
295             }
296         }
297         public Date getDate() {
298             ensureType(ItemType.generalData);
299             return date.getValue();
300         }
301         public void setDate(Date date) {
302             ensureType(ItemType.generalData);
303             this.date.setValue(date);
304         }
305         public void setDate(String text) {
306             if ((text == null) || text.trim()
307                                       .isEmpty())
308             {
309                 setDate((Date) null);
310                 return;
311             }
312
313             int year, month, day;
314             final Calendar c = GregorianCalendar.getInstance();
315             Matcher m = reYMD.matcher(text);
316             if (m.matches()) {
317                 year = Integer.parseInt(m.group(1));
318                 month = Integer.parseInt(m.group(2)) - 1;   // month is 0-based
319                 day = Integer.parseInt(m.group(3));
320             }
321             else {
322                 year = c.get(Calendar.YEAR);
323                 m = reMD.matcher(text);
324                 if (m.matches()) {
325                     month = Integer.parseInt(m.group(1)) - 1;
326                     day = Integer.parseInt(m.group(2));
327                 }
328                 else {
329                     month = c.get(Calendar.MONTH);
330                     m = reD.matcher(text);
331                     if (m.matches()) {
332                         day = Integer.parseInt(m.group(1));
333                     }
334                     else {
335                         day = c.get(Calendar.DAY_OF_MONTH);
336                     }
337                 }
338             }
339
340             c.set(year, month, day);
341
342             this.setDate(c.getTime());
343         }
344         void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
345                          @NonNull androidx.lifecycle.Observer<? super Date> observer) {
346             this.date.observe(owner, observer);
347         }
348         void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
349             this.date.removeObserver(observer);
350         }
351         public String getDescription() {
352             ensureType(ItemType.generalData);
353             return description.getValue();
354         }
355         public void setDescription(String description) {
356             ensureType(ItemType.generalData);
357             this.description.setValue(description);
358         }
359         void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
360                                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
361             this.description.observe(owner, observer);
362         }
363         void stopObservingDescription(
364                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
365             this.description.removeObserver(observer);
366         }
367         public LedgerTransactionAccount getAccount() {
368             ensureType(ItemType.transactionRow);
369             return account;
370         }
371         public void setAccountName(String name) {
372             account.setAccountName(name);
373         }
374         /**
375          * getFormattedDate()
376          *
377          * @return nicely formatted, shortest available date representation
378          */
379         String getFormattedDate() {
380             if (date == null)
381                 return null;
382             Date time = date.getValue();
383             if (time == null)
384                 return null;
385
386             Calendar c = GregorianCalendar.getInstance();
387             c.setTime(time);
388             Calendar today = GregorianCalendar.getInstance();
389
390             final int myYear = c.get(Calendar.YEAR);
391             final int myMonth = c.get(Calendar.MONTH);
392             final int myDay = c.get(Calendar.DAY_OF_MONTH);
393
394             if (today.get(Calendar.YEAR) != myYear) {
395                 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth + 1, myDay);
396             }
397
398             if (today.get(Calendar.MONTH) != myMonth) {
399                 return String.format(Locale.US, "%d/%02d", myMonth + 1, myDay);
400             }
401
402             return String.valueOf(myDay);
403         }
404         void observeEditableFlag(NewTransactionActivity activity, Observer<Boolean> observer) {
405             editable.observe(activity, observer);
406         }
407         void stopObservingEditableFlag(Observer<Boolean> observer) {
408             editable.removeObserver(observer);
409         }
410         void observeCommentVisible(NewTransactionActivity activity, Observer<Boolean> observer) {
411             commentVisible.observe(activity, observer);
412         }
413         void stopObservingCommentVisible(Observer<Boolean> observer) {
414             commentVisible.removeObserver(observer);
415         }
416         void observeComment(NewTransactionActivity activity, Observer<String> observer) {
417             comment.observe(activity, observer);
418         }
419         void stopObservingComment(Observer<String> observer) {
420             comment.removeObserver(observer);
421         }
422         public void setComment(String comment) {
423             getAccount().setComment(comment);
424             this.comment.postValue(comment);
425         }
426         public Currency getCurrency() {
427             return this.currency.getValue();
428         }
429         public void setCurrency(Currency currency) {
430             Currency present = this.currency.getValue();
431             if ((currency == null) && (present != null) ||
432                 (currency != null) && !currency.equals(present))
433             {
434                 getAccount().setCurrency((currency != null && !currency.getName()
435                                                                        .isEmpty())
436                                          ? currency.getName() : null);
437                 this.currency.setValue(currency);
438             }
439         }
440         void observeCurrency(NewTransactionActivity activity, Observer<Currency> observer) {
441             currency.observe(activity, observer);
442         }
443         void stopObservingCurrency(Observer<Currency> observer) {
444             currency.removeObserver(observer);
445         }
446         boolean isOfType(ItemType type) {
447             return this.type == type;
448         }
449         boolean isAmountHintSet() {
450             return amountHintIsSet;
451         }
452     }
453 }