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.
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.
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/>.
18 package net.ktnx.mobileledger.ui.activity;
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;
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;
32 import org.jetbrains.annotations.NotNull;
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;
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 final MutableLiveData<Boolean> showComments = new MutableLiveData<>(false);
63 void observeShowComments(LifecycleOwner owner, Observer<? super Boolean> observer) {
64 showComments.observe(owner, observer);
66 void observeBusyFlag(@NonNull LifecycleOwner owner, Observer<? super Boolean> observer) {
67 busyFlag.observe(owner, observer);
69 void observeDataProfile(LifecycleOwner activity) {
70 if (!observingDataProfile)
71 Data.profile.observe(activity, profileObserver);
72 observingDataProfile = true;
74 boolean getSimulateSave() {
75 return simulateSave.getValue();
77 public void setSimulateSave(boolean simulateSave) {
78 this.simulateSave.setValue(simulateSave);
80 void toggleSimulateSave() {
81 simulateSave.setValue(!simulateSave.getValue());
83 void observeSimulateSave(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
84 @NonNull androidx.lifecycle.Observer<? super Boolean> observer) {
85 this.simulateSave.observe(owner, observer);
87 int getAccountCount() {
90 public Date getDate() {
91 return header.date.getValue();
93 public String getDescription() {
94 return header.description.getValue();
96 public String getComment() {
97 return header.comment.getValue();
99 LiveData<Boolean> isSubmittable() {
100 return this.isSubmittable;
103 header.date.setValue(null);
104 header.description.setValue(null);
105 header.comment.setValue(null);
107 items.add(new Item(this, new LedgerTransactionAccount("")));
108 items.add(new Item(this, new LedgerTransactionAccount("")));
109 focusedItem.setValue(0);
111 void observeFocusedItem(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
112 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
113 this.focusedItem.observe(owner, observer);
115 void stopObservingFocusedItem(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
116 this.focusedItem.removeObserver(observer);
118 void observeAccountCount(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
119 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
120 this.accountCount.observe(owner, observer);
122 void stopObservingAccountCount(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
123 this.accountCount.removeObserver(observer);
125 int getFocusedItem() { return focusedItem.getValue(); }
126 void setFocusedItem(int position) {
127 focusedItem.setValue(position);
129 int addAccount(LedgerTransactionAccount acc) {
130 items.add(new Item(this, acc));
131 accountCount.setValue(getAccountCount());
134 boolean accountsInInitialState() {
135 for (Item item : items) {
136 LedgerTransactionAccount acc = item.getAccount();
137 if (acc.isAmountSet())
139 if (!acc.getAccountName()
147 LedgerTransactionAccount getAccount(int index) {
148 return items.get(index)
151 Item getItem(int index) {
156 if (index <= items.size())
157 return items.get(index - 1);
161 void removeRow(Item item, NewTransactionItemsAdapter adapter) {
162 int pos = items.indexOf(item);
164 if (adapter != null) {
165 adapter.notifyItemRemoved(pos + 1);
166 sendCountNotifications();
169 void removeItem(int pos) {
171 accountCount.setValue(getAccountCount());
173 void sendCountNotifications() {
174 accountCount.setValue(getAccountCount());
176 public void sendFocusedNotification() {
177 focusedItem.setValue(focusedItem.getValue());
179 void updateFocusedItem(int position) {
180 focusedItem.setValue(position);
182 void noteFocusChanged(int position, FocusedElement element) {
183 getItem(position).setFocusedElement(element);
185 void swapItems(int one, int two) {
186 Collections.swap(items, one - 1, two - 1);
188 void moveItemLast(int index) {
192 3 <-- desired position
194 int itemCount = items.size();
196 if (index < itemCount - 1) {
197 Item acc = items.remove(index);
198 items.add(itemCount - 1, acc);
201 void toggleCurrencyVisible() {
202 showCurrency.setValue(!showCurrency.getValue());
204 void stopObservingBusyFlag(Observer<Boolean> observer) {
205 busyFlag.removeObserver(observer);
207 void incrementBusyCounter() {
208 int newValue = busyCounter.incrementAndGet();
209 if (newValue == 1) busyFlag.postValue(true);
211 void decrementBusyCounter() {
212 int newValue = busyCounter.decrementAndGet();
213 if (newValue == 0) busyFlag.postValue(false);
215 public boolean getBusyFlag() {
216 return busyFlag.getValue();
218 public void toggleShowComments() {
219 showComments.setValue(!showComments.getValue());
221 enum ItemType {generalData, transactionRow, bottomFiller}
223 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
226 //==========================================================================================
230 private ItemType type;
231 private MutableLiveData<Date> 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 boolean amountHintIsSet = false;
241 Item(NewTransactionModel model) {
243 type = ItemType.bottomFiller;
244 editable.setValue(false);
246 Item(NewTransactionModel model, Date date, String description) {
248 this.type = ItemType.generalData;
249 this.date.setValue(date);
250 this.description.setValue(description);
251 this.editable.setValue(true);
253 Item(NewTransactionModel model, LedgerTransactionAccount account) {
255 this.type = ItemType.transactionRow;
256 this.account = account;
257 String currName = account.getCurrency();
258 Currency curr = null;
259 if ((currName != null) && !currName.isEmpty())
260 curr = Currency.loadByName(currName);
261 this.currency.setValue(curr);
262 this.editable.setValue(true);
264 FocusedElement getFocusedElement() {
265 return focusedElement;
267 void setFocusedElement(FocusedElement focusedElement) {
268 this.focusedElement = focusedElement;
270 public NewTransactionModel getModel() {
273 void setEditable(boolean editable) {
274 ensureType(ItemType.generalData, ItemType.transactionRow);
275 this.editable.setValue(editable);
277 private void ensureType(ItemType type1, ItemType type2) {
278 if ((type != type1) && (type != type2)) {
279 throw new RuntimeException(
280 String.format("Actual type (%s) differs from wanted (%s or %s)", type,
284 String getAmountHint() {
285 ensureType(ItemType.transactionRow);
286 return amountHint.getValue();
288 void setAmountHint(String amountHint) {
289 ensureType(ItemType.transactionRow);
291 // avoid unnecessary triggers
292 if (amountHint == null) {
293 if (this.amountHint.getValue() == null)
295 amountHintIsSet = false;
298 if (amountHint.equals(this.amountHint.getValue()))
300 amountHintIsSet = true;
303 this.amountHint.setValue(amountHint);
305 void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
306 @NonNull androidx.lifecycle.Observer<? super String> observer) {
307 this.amountHint.observe(owner, observer);
309 void stopObservingAmountHint(
310 @NonNull androidx.lifecycle.Observer<? super String> observer) {
311 this.amountHint.removeObserver(observer);
316 void ensureType(ItemType wantedType) {
317 if (type != wantedType) {
318 throw new RuntimeException(
319 String.format("Actual type (%s) differs from wanted (%s)", type,
323 public Date getDate() {
324 ensureType(ItemType.generalData);
325 return date.getValue();
327 public void setDate(Date date) {
328 ensureType(ItemType.generalData);
329 this.date.setValue(date);
331 public void setDate(String text) {
332 if ((text == null) || text.trim()
335 setDate((Date) null);
339 int year, month, day;
340 final Calendar c = GregorianCalendar.getInstance();
341 Matcher m = reYMD.matcher(text);
343 year = Integer.parseInt(m.group(1));
344 month = Integer.parseInt(m.group(2)) - 1; // month is 0-based
345 day = Integer.parseInt(m.group(3));
348 year = c.get(Calendar.YEAR);
349 m = reMD.matcher(text);
351 month = Integer.parseInt(m.group(1)) - 1;
352 day = Integer.parseInt(m.group(2));
355 month = c.get(Calendar.MONTH);
356 m = reD.matcher(text);
358 day = Integer.parseInt(m.group(1));
361 day = c.get(Calendar.DAY_OF_MONTH);
366 c.set(year, month, day);
368 this.setDate(c.getTime());
370 void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
371 @NonNull androidx.lifecycle.Observer<? super Date> observer) {
372 this.date.observe(owner, observer);
374 void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
375 this.date.removeObserver(observer);
377 public String getDescription() {
378 ensureType(ItemType.generalData);
379 return description.getValue();
381 public void setDescription(String description) {
382 ensureType(ItemType.generalData);
383 this.description.setValue(description);
385 void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
386 @NonNull androidx.lifecycle.Observer<? super String> observer) {
387 this.description.observe(owner, observer);
389 void stopObservingDescription(
390 @NonNull androidx.lifecycle.Observer<? super String> observer) {
391 this.description.removeObserver(observer);
393 public String getTransactionComment() {
394 ensureType(ItemType.generalData);
395 return comment.getValue();
397 public void setTransactionComment(String transactionComment) {
398 ensureType(ItemType.generalData);
399 this.comment.setValue(transactionComment);
401 void observeTransactionComment(@NonNull @NotNull LifecycleOwner owner,
402 @NonNull Observer<? super String> observer) {
403 ensureType(ItemType.generalData);
404 this.comment.observe(owner, observer);
406 void stopObservingTransactionComment(@NonNull Observer<? super String> observer) {
407 ensureType(ItemType.generalData);
408 this.comment.removeObserver(observer);
410 public LedgerTransactionAccount getAccount() {
411 ensureType(ItemType.transactionRow);
414 public void setAccountName(String name) {
415 account.setAccountName(name);
420 * @return nicely formatted, shortest available date representation
422 String getFormattedDate() {
425 Date time = date.getValue();
429 Calendar c = GregorianCalendar.getInstance();
431 Calendar today = GregorianCalendar.getInstance();
433 final int myYear = c.get(Calendar.YEAR);
434 final int myMonth = c.get(Calendar.MONTH);
435 final int myDay = c.get(Calendar.DAY_OF_MONTH);
437 if (today.get(Calendar.YEAR) != myYear) {
438 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth + 1, myDay);
441 if (today.get(Calendar.MONTH) != myMonth) {
442 return String.format(Locale.US, "%d/%02d", myMonth + 1, myDay);
445 return String.valueOf(myDay);
447 void observeEditableFlag(NewTransactionActivity activity, Observer<Boolean> observer) {
448 editable.observe(activity, observer);
450 void stopObservingEditableFlag(Observer<Boolean> observer) {
451 editable.removeObserver(observer);
453 void observeComment(NewTransactionActivity activity, Observer<String> observer) {
454 comment.observe(activity, observer);
456 void stopObservingComment(Observer<String> observer) {
457 comment.removeObserver(observer);
459 public void setComment(String comment) {
460 getAccount().setComment(comment);
461 this.comment.postValue(comment);
463 public Currency getCurrency() {
464 return this.currency.getValue();
466 public void setCurrency(Currency currency) {
467 Currency present = this.currency.getValue();
468 if ((currency == null) && (present != null) ||
469 (currency != null) && !currency.equals(present))
471 getAccount().setCurrency((currency != null && !currency.getName()
473 ? currency.getName() : null);
474 this.currency.setValue(currency);
477 void observeCurrency(NewTransactionActivity activity, Observer<Currency> observer) {
478 currency.observe(activity, observer);
480 void stopObservingCurrency(Observer<Currency> observer) {
481 currency.removeObserver(observer);
483 boolean isOfType(ItemType type) {
484 return this.type == type;
486 boolean isAmountHintSet() {
487 return amountHintIsSet;