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