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