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