]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionModel.java
whitespace
[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 =
62             profile -> showCurrency.postValue(profile.getShowCommodityByDefault());
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)
210             busyFlag.postValue(true);
211     }
212     void decrementBusyCounter() {
213         int newValue = busyCounter.decrementAndGet();
214         if (newValue == 0)
215             busyFlag.postValue(false);
216     }
217     public boolean getBusyFlag() {
218         return busyFlag.getValue();
219     }
220     public void toggleShowComments() {
221         showComments.setValue(!showComments.getValue());
222     }
223     enum ItemType {generalData, transactionRow, bottomFiller}
224
225     enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
226
227
228     //==========================================================================================
229
230
231     static class Item {
232         private ItemType type;
233         private MutableLiveData<Date> date = new MutableLiveData<>();
234         private MutableLiveData<String> description = new MutableLiveData<>();
235         private LedgerTransactionAccount account;
236         private MutableLiveData<String> amountHint = new MutableLiveData<>(null);
237         private NewTransactionModel model;
238         private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
239         private FocusedElement focusedElement = FocusedElement.Account;
240         private MutableLiveData<String> comment = new MutableLiveData<>(null);
241         private MutableLiveData<Currency> currency = new MutableLiveData<>(null);
242         private boolean amountHintIsSet = false;
243         Item(NewTransactionModel model) {
244             this.model = model;
245             type = ItemType.bottomFiller;
246             editable.setValue(false);
247         }
248         Item(NewTransactionModel model, Date date, String description) {
249             this.model = model;
250             this.type = ItemType.generalData;
251             this.date.setValue(date);
252             this.description.setValue(description);
253             this.editable.setValue(true);
254         }
255         Item(NewTransactionModel model, LedgerTransactionAccount account) {
256             this.model = model;
257             this.type = ItemType.transactionRow;
258             this.account = account;
259             String currName = account.getCurrency();
260             Currency curr = null;
261             if ((currName != null) && !currName.isEmpty())
262                 curr = Currency.loadByName(currName);
263             this.currency.setValue(curr);
264             this.editable.setValue(true);
265         }
266         FocusedElement getFocusedElement() {
267             return focusedElement;
268         }
269         void setFocusedElement(FocusedElement focusedElement) {
270             this.focusedElement = focusedElement;
271         }
272         public NewTransactionModel getModel() {
273             return model;
274         }
275         void setEditable(boolean editable) {
276             ensureType(ItemType.generalData, ItemType.transactionRow);
277             this.editable.setValue(editable);
278         }
279         private void ensureType(ItemType type1, ItemType type2) {
280             if ((type != type1) && (type != type2)) {
281                 throw new RuntimeException(
282                         String.format("Actual type (%s) differs from wanted (%s or %s)", type,
283                                 type1, type2));
284             }
285         }
286         String getAmountHint() {
287             ensureType(ItemType.transactionRow);
288             return amountHint.getValue();
289         }
290         void setAmountHint(String amountHint) {
291             ensureType(ItemType.transactionRow);
292
293             // avoid unnecessary triggers
294             if (amountHint == null) {
295                 if (this.amountHint.getValue() == null)
296                     return;
297                 amountHintIsSet = false;
298             }
299             else {
300                 if (amountHint.equals(this.amountHint.getValue()))
301                     return;
302                 amountHintIsSet = true;
303             }
304
305             this.amountHint.setValue(amountHint);
306         }
307         void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
308                                @NonNull androidx.lifecycle.Observer<? super String> observer) {
309             this.amountHint.observe(owner, observer);
310         }
311         void stopObservingAmountHint(
312                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
313             this.amountHint.removeObserver(observer);
314         }
315         ItemType getType() {
316             return type;
317         }
318         void ensureType(ItemType wantedType) {
319             if (type != wantedType) {
320                 throw new RuntimeException(
321                         String.format("Actual type (%s) differs from wanted (%s)", type,
322                                 wantedType));
323             }
324         }
325         public Date getDate() {
326             ensureType(ItemType.generalData);
327             return date.getValue();
328         }
329         public void setDate(Date date) {
330             ensureType(ItemType.generalData);
331             this.date.setValue(date);
332         }
333         public void setDate(String text) {
334             if ((text == null) || text.trim()
335                                       .isEmpty())
336             {
337                 setDate((Date) null);
338                 return;
339             }
340
341             int year, month, day;
342             final Calendar c = GregorianCalendar.getInstance();
343             Matcher m = reYMD.matcher(text);
344             if (m.matches()) {
345                 year = Integer.parseInt(m.group(1));
346                 month = Integer.parseInt(m.group(2)) - 1;   // month is 0-based
347                 day = Integer.parseInt(m.group(3));
348             }
349             else {
350                 year = c.get(Calendar.YEAR);
351                 m = reMD.matcher(text);
352                 if (m.matches()) {
353                     month = Integer.parseInt(m.group(1)) - 1;
354                     day = Integer.parseInt(m.group(2));
355                 }
356                 else {
357                     month = c.get(Calendar.MONTH);
358                     m = reD.matcher(text);
359                     if (m.matches()) {
360                         day = Integer.parseInt(m.group(1));
361                     }
362                     else {
363                         day = c.get(Calendar.DAY_OF_MONTH);
364                     }
365                 }
366             }
367
368             c.set(year, month, day);
369
370             this.setDate(c.getTime());
371         }
372         void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
373                          @NonNull androidx.lifecycle.Observer<? super Date> observer) {
374             this.date.observe(owner, observer);
375         }
376         void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
377             this.date.removeObserver(observer);
378         }
379         public String getDescription() {
380             ensureType(ItemType.generalData);
381             return description.getValue();
382         }
383         public void setDescription(String description) {
384             ensureType(ItemType.generalData);
385             this.description.setValue(description);
386         }
387         void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
388                                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
389             this.description.observe(owner, observer);
390         }
391         void stopObservingDescription(
392                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
393             this.description.removeObserver(observer);
394         }
395         public String getTransactionComment() {
396             ensureType(ItemType.generalData);
397             return comment.getValue();
398         }
399         public void setTransactionComment(String transactionComment) {
400             ensureType(ItemType.generalData);
401             this.comment.setValue(transactionComment);
402         }
403         void observeTransactionComment(@NonNull @NotNull LifecycleOwner owner,
404                                        @NonNull Observer<? super String> observer) {
405             ensureType(ItemType.generalData);
406             this.comment.observe(owner, observer);
407         }
408         void stopObservingTransactionComment(@NonNull Observer<? super String> observer) {
409             ensureType(ItemType.generalData);
410             this.comment.removeObserver(observer);
411         }
412         public LedgerTransactionAccount getAccount() {
413             ensureType(ItemType.transactionRow);
414             return account;
415         }
416         public void setAccountName(String name) {
417             account.setAccountName(name);
418         }
419         /**
420          * getFormattedDate()
421          *
422          * @return nicely formatted, shortest available date representation
423          */
424         String getFormattedDate() {
425             if (date == null)
426                 return null;
427             Date time = date.getValue();
428             if (time == null)
429                 return null;
430
431             Calendar c = GregorianCalendar.getInstance();
432             c.setTime(time);
433             Calendar today = GregorianCalendar.getInstance();
434
435             final int myYear = c.get(Calendar.YEAR);
436             final int myMonth = c.get(Calendar.MONTH);
437             final int myDay = c.get(Calendar.DAY_OF_MONTH);
438
439             if (today.get(Calendar.YEAR) != myYear) {
440                 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth + 1, myDay);
441             }
442
443             if (today.get(Calendar.MONTH) != myMonth) {
444                 return String.format(Locale.US, "%d/%02d", myMonth + 1, myDay);
445             }
446
447             return String.valueOf(myDay);
448         }
449         void observeEditableFlag(NewTransactionActivity activity, Observer<Boolean> observer) {
450             editable.observe(activity, observer);
451         }
452         void stopObservingEditableFlag(Observer<Boolean> observer) {
453             editable.removeObserver(observer);
454         }
455         void observeComment(NewTransactionActivity activity, Observer<String> observer) {
456             comment.observe(activity, observer);
457         }
458         void stopObservingComment(Observer<String> observer) {
459             comment.removeObserver(observer);
460         }
461         public void setComment(String comment) {
462             getAccount().setComment(comment);
463             this.comment.postValue(comment);
464         }
465         public Currency getCurrency() {
466             return this.currency.getValue();
467         }
468         public void setCurrency(Currency currency) {
469             Currency present = this.currency.getValue();
470             if ((currency == null) && (present != null) ||
471                 (currency != null) && !currency.equals(present))
472             {
473                 getAccount().setCurrency((currency != null && !currency.getName()
474                                                                        .isEmpty())
475                                          ? currency.getName() : null);
476                 this.currency.setValue(currency);
477             }
478         }
479         void observeCurrency(NewTransactionActivity activity, Observer<Currency> observer) {
480             currency.observe(activity, observer);
481         }
482         void stopObservingCurrency(Observer<Currency> observer) {
483             currency.removeObserver(observer);
484         }
485         boolean isOfType(ItemType type) {
486             return this.type == type;
487         }
488         boolean isAmountHintSet() {
489             return amountHintIsSet;
490         }
491     }
492 }