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