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