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 final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
53 private final Item header = new Item(this, null, "");
54 private final Item trailer = new Item(this);
55 private final MutableLiveData<Integer> focusedItem = new MutableLiveData<>(0);
56 private final MutableLiveData<Integer> accountCount = new MutableLiveData<>(0);
57 private final MutableLiveData<Boolean> simulateSave = new MutableLiveData<>(false);
58 private final AtomicInteger busyCounter = new AtomicInteger(0);
59 private final MutableLiveData<Boolean> busyFlag = new MutableLiveData<>(false);
60 private boolean observingDataProfile;
61 private Observer<MobileLedgerProfile> profileObserver =
62 profile -> showCurrency.postValue(profile.getShowCommodityByDefault());
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();
210 busyFlag.postValue(true);
212 void decrementBusyCounter() {
213 int newValue = busyCounter.decrementAndGet();
215 busyFlag.postValue(false);
217 public boolean getBusyFlag() {
218 return busyFlag.getValue();
220 public void toggleShowComments() {
221 showComments.setValue(!showComments.getValue());
223 enum ItemType {generalData, transactionRow, bottomFiller}
225 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
228 //==========================================================================================
232 private ItemType type;
233 private MutableLiveData<Date> date = new MutableLiveData<>();
234 private MutableLiveData<String> description = new MutableLiveData<>();
235 private LedgerTransactionAccount account;
236 private MutableLiveData<String> amountHint = new MutableLiveData<>(null);
237 private NewTransactionModel model;
238 private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
239 private FocusedElement focusedElement = FocusedElement.Account;
240 private MutableLiveData<String> comment = new MutableLiveData<>(null);
241 private MutableLiveData<Currency> currency = new MutableLiveData<>(null);
242 private boolean amountHintIsSet = false;
243 Item(NewTransactionModel model) {
245 type = ItemType.bottomFiller;
246 editable.setValue(false);
248 Item(NewTransactionModel model, Date date, String description) {
250 this.type = ItemType.generalData;
251 this.date.setValue(date);
252 this.description.setValue(description);
253 this.editable.setValue(true);
255 Item(NewTransactionModel model, LedgerTransactionAccount account) {
257 this.type = ItemType.transactionRow;
258 this.account = account;
259 String currName = account.getCurrency();
260 Currency curr = null;
261 if ((currName != null) && !currName.isEmpty())
262 curr = Currency.loadByName(currName);
263 this.currency.setValue(curr);
264 this.editable.setValue(true);
266 FocusedElement getFocusedElement() {
267 return focusedElement;
269 void setFocusedElement(FocusedElement focusedElement) {
270 this.focusedElement = focusedElement;
272 public NewTransactionModel getModel() {
275 void setEditable(boolean editable) {
276 ensureType(ItemType.generalData, ItemType.transactionRow);
277 this.editable.setValue(editable);
279 private void ensureType(ItemType type1, ItemType type2) {
280 if ((type != type1) && (type != type2)) {
281 throw new RuntimeException(
282 String.format("Actual type (%s) differs from wanted (%s or %s)", type,
286 String getAmountHint() {
287 ensureType(ItemType.transactionRow);
288 return amountHint.getValue();
290 void setAmountHint(String amountHint) {
291 ensureType(ItemType.transactionRow);
293 // avoid unnecessary triggers
294 if (amountHint == null) {
295 if (this.amountHint.getValue() == null)
297 amountHintIsSet = false;
300 if (amountHint.equals(this.amountHint.getValue()))
302 amountHintIsSet = true;
305 this.amountHint.setValue(amountHint);
307 void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
308 @NonNull androidx.lifecycle.Observer<? super String> observer) {
309 this.amountHint.observe(owner, observer);
311 void stopObservingAmountHint(
312 @NonNull androidx.lifecycle.Observer<? super String> observer) {
313 this.amountHint.removeObserver(observer);
318 void ensureType(ItemType wantedType) {
319 if (type != wantedType) {
320 throw new RuntimeException(
321 String.format("Actual type (%s) differs from wanted (%s)", type,
325 public Date getDate() {
326 ensureType(ItemType.generalData);
327 return date.getValue();
329 public void setDate(Date date) {
330 ensureType(ItemType.generalData);
331 this.date.setValue(date);
333 public void setDate(String text) {
334 if ((text == null) || text.trim()
337 setDate((Date) null);
341 int year, month, day;
342 final Calendar c = GregorianCalendar.getInstance();
343 Matcher m = reYMD.matcher(text);
345 year = Integer.parseInt(m.group(1));
346 month = Integer.parseInt(m.group(2)) - 1; // month is 0-based
347 day = Integer.parseInt(m.group(3));
350 year = c.get(Calendar.YEAR);
351 m = reMD.matcher(text);
353 month = Integer.parseInt(m.group(1)) - 1;
354 day = Integer.parseInt(m.group(2));
357 month = c.get(Calendar.MONTH);
358 m = reD.matcher(text);
360 day = Integer.parseInt(m.group(1));
363 day = c.get(Calendar.DAY_OF_MONTH);
368 c.set(year, month, day);
370 this.setDate(c.getTime());
372 void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
373 @NonNull androidx.lifecycle.Observer<? super Date> observer) {
374 this.date.observe(owner, observer);
376 void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
377 this.date.removeObserver(observer);
379 public String getDescription() {
380 ensureType(ItemType.generalData);
381 return description.getValue();
383 public void setDescription(String description) {
384 ensureType(ItemType.generalData);
385 this.description.setValue(description);
387 void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
388 @NonNull androidx.lifecycle.Observer<? super String> observer) {
389 this.description.observe(owner, observer);
391 void stopObservingDescription(
392 @NonNull androidx.lifecycle.Observer<? super String> observer) {
393 this.description.removeObserver(observer);
395 public String getTransactionComment() {
396 ensureType(ItemType.generalData);
397 return comment.getValue();
399 public void setTransactionComment(String transactionComment) {
400 ensureType(ItemType.generalData);
401 this.comment.setValue(transactionComment);
403 void observeTransactionComment(@NonNull @NotNull LifecycleOwner owner,
404 @NonNull Observer<? super String> observer) {
405 ensureType(ItemType.generalData);
406 this.comment.observe(owner, observer);
408 void stopObservingTransactionComment(@NonNull Observer<? super String> observer) {
409 ensureType(ItemType.generalData);
410 this.comment.removeObserver(observer);
412 public LedgerTransactionAccount getAccount() {
413 ensureType(ItemType.transactionRow);
416 public void setAccountName(String name) {
417 account.setAccountName(name);
422 * @return nicely formatted, shortest available date representation
424 String getFormattedDate() {
427 Date time = date.getValue();
431 Calendar c = GregorianCalendar.getInstance();
433 Calendar today = GregorianCalendar.getInstance();
435 final int myYear = c.get(Calendar.YEAR);
436 final int myMonth = c.get(Calendar.MONTH);
437 final int myDay = c.get(Calendar.DAY_OF_MONTH);
439 if (today.get(Calendar.YEAR) != myYear) {
440 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth + 1, myDay);
443 if (today.get(Calendar.MONTH) != myMonth) {
444 return String.format(Locale.US, "%d/%02d", myMonth + 1, myDay);
447 return String.valueOf(myDay);
449 void observeEditableFlag(NewTransactionActivity activity, Observer<Boolean> observer) {
450 editable.observe(activity, observer);
452 void stopObservingEditableFlag(Observer<Boolean> observer) {
453 editable.removeObserver(observer);
455 void observeComment(NewTransactionActivity activity, Observer<String> observer) {
456 comment.observe(activity, observer);
458 void stopObservingComment(Observer<String> observer) {
459 comment.removeObserver(observer);
461 public void setComment(String comment) {
462 getAccount().setComment(comment);
463 this.comment.postValue(comment);
465 public Currency getCurrency() {
466 return this.currency.getValue();
468 public void setCurrency(Currency currency) {
469 Currency present = this.currency.getValue();
470 if ((currency == null) && (present != null) ||
471 (currency != null) && !currency.equals(present))
473 getAccount().setCurrency((currency != null && !currency.getName()
475 ? currency.getName() : null);
476 this.currency.setValue(currency);
479 void observeCurrency(NewTransactionActivity activity, Observer<Currency> observer) {
480 currency.observe(activity, observer);
482 void stopObservingCurrency(Observer<Currency> observer) {
483 currency.removeObserver(observer);
485 boolean isOfType(ItemType type) {
486 return this.type == type;
488 boolean isAmountHintSet() {
489 return amountHintIsSet;