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