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 = profile -> {
62 showCurrency.postValue(profile.getShowCommodityByDefault());
63 showComments.postValue(profile.getShowCommentsByDefault());
65 void observeShowComments(LifecycleOwner owner, Observer<? super Boolean> observer) {
66 showComments.observe(owner, observer);
68 void observeBusyFlag(@NonNull LifecycleOwner owner, Observer<? super Boolean> observer) {
69 busyFlag.observe(owner, observer);
71 void observeDataProfile(LifecycleOwner activity) {
72 if (!observingDataProfile)
73 Data.profile.observe(activity, profileObserver);
74 observingDataProfile = true;
76 boolean getSimulateSave() {
77 return simulateSave.getValue();
79 public void setSimulateSave(boolean simulateSave) {
80 this.simulateSave.setValue(simulateSave);
82 void toggleSimulateSave() {
83 simulateSave.setValue(!simulateSave.getValue());
85 void observeSimulateSave(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
86 @NonNull androidx.lifecycle.Observer<? super Boolean> observer) {
87 this.simulateSave.observe(owner, observer);
89 int getAccountCount() {
92 public Date getDate() {
93 return header.date.getValue();
95 public String getDescription() {
96 return header.description.getValue();
98 public String getComment() {
99 return header.comment.getValue();
101 LiveData<Boolean> isSubmittable() {
102 return this.isSubmittable;
105 header.date.setValue(null);
106 header.description.setValue(null);
107 header.comment.setValue(null);
109 items.add(new Item(this, new LedgerTransactionAccount("")));
110 items.add(new Item(this, new LedgerTransactionAccount("")));
111 focusedItem.setValue(0);
113 void observeFocusedItem(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
114 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
115 this.focusedItem.observe(owner, observer);
117 void stopObservingFocusedItem(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
118 this.focusedItem.removeObserver(observer);
120 void observeAccountCount(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
121 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
122 this.accountCount.observe(owner, observer);
124 void stopObservingAccountCount(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
125 this.accountCount.removeObserver(observer);
127 int getFocusedItem() { return focusedItem.getValue(); }
128 void setFocusedItem(int position) {
129 focusedItem.setValue(position);
131 int addAccount(LedgerTransactionAccount acc) {
132 items.add(new Item(this, acc));
133 accountCount.setValue(getAccountCount());
136 boolean accountsInInitialState() {
137 for (Item item : items) {
138 LedgerTransactionAccount acc = item.getAccount();
139 if (acc.isAmountSet())
141 if (!acc.getAccountName()
149 LedgerTransactionAccount getAccount(int index) {
150 return items.get(index)
153 Item getItem(int index) {
158 if (index <= items.size())
159 return items.get(index - 1);
163 void removeRow(Item item, NewTransactionItemsAdapter adapter) {
164 int pos = items.indexOf(item);
166 if (adapter != null) {
167 adapter.notifyItemRemoved(pos + 1);
168 sendCountNotifications();
171 void removeItem(int pos) {
173 accountCount.setValue(getAccountCount());
175 void sendCountNotifications() {
176 accountCount.setValue(getAccountCount());
178 public void sendFocusedNotification() {
179 focusedItem.setValue(focusedItem.getValue());
181 void updateFocusedItem(int position) {
182 focusedItem.setValue(position);
184 void noteFocusChanged(int position, FocusedElement element) {
185 getItem(position).setFocusedElement(element);
187 void swapItems(int one, int two) {
188 Collections.swap(items, one - 1, two - 1);
190 void moveItemLast(int index) {
194 3 <-- desired position
196 int itemCount = items.size();
198 if (index < itemCount - 1) {
199 Item acc = items.remove(index);
200 items.add(itemCount - 1, acc);
203 void toggleCurrencyVisible() {
204 showCurrency.setValue(!showCurrency.getValue());
206 void stopObservingBusyFlag(Observer<Boolean> observer) {
207 busyFlag.removeObserver(observer);
209 void incrementBusyCounter() {
210 int newValue = busyCounter.incrementAndGet();
212 busyFlag.postValue(true);
214 void decrementBusyCounter() {
215 int newValue = busyCounter.decrementAndGet();
217 busyFlag.postValue(false);
219 public boolean getBusyFlag() {
220 return busyFlag.getValue();
222 public void toggleShowComments() {
223 showComments.setValue(!showComments.getValue());
225 enum ItemType {generalData, transactionRow, bottomFiller}
227 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
230 //==========================================================================================
234 private ItemType type;
235 private MutableLiveData<Date> date = new MutableLiveData<>();
236 private MutableLiveData<String> description = new MutableLiveData<>();
237 private LedgerTransactionAccount account;
238 private MutableLiveData<String> amountHint = new MutableLiveData<>(null);
239 private NewTransactionModel model;
240 private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
241 private FocusedElement focusedElement = FocusedElement.Account;
242 private MutableLiveData<String> comment = new MutableLiveData<>(null);
243 private MutableLiveData<Currency> currency = new MutableLiveData<>(null);
244 private MutableLiveData<Boolean> amountValid = new MutableLiveData<>(true);
245 private boolean amountHintIsSet = false;
246 Item(NewTransactionModel model) {
248 type = ItemType.bottomFiller;
249 editable.setValue(false);
251 Item(NewTransactionModel model, Date date, String description) {
253 this.type = ItemType.generalData;
254 this.date.setValue(date);
255 this.description.setValue(description);
256 this.editable.setValue(true);
258 Item(NewTransactionModel model, LedgerTransactionAccount account) {
260 this.type = ItemType.transactionRow;
261 this.account = account;
262 String currName = account.getCurrency();
263 Currency curr = null;
264 if ((currName != null) && !currName.isEmpty())
265 curr = Currency.loadByName(currName);
266 this.currency.setValue(curr);
267 this.editable.setValue(true);
269 FocusedElement getFocusedElement() {
270 return focusedElement;
272 void setFocusedElement(FocusedElement focusedElement) {
273 this.focusedElement = focusedElement;
275 public NewTransactionModel getModel() {
278 void setEditable(boolean editable) {
279 ensureType(ItemType.generalData, ItemType.transactionRow);
280 this.editable.setValue(editable);
282 private void ensureType(ItemType type1, ItemType type2) {
283 if ((type != type1) && (type != type2)) {
284 throw new RuntimeException(
285 String.format("Actual type (%s) differs from wanted (%s or %s)", type,
289 String getAmountHint() {
290 ensureType(ItemType.transactionRow);
291 return amountHint.getValue();
293 void setAmountHint(String amountHint) {
294 ensureType(ItemType.transactionRow);
296 // avoid unnecessary triggers
297 if (amountHint == null) {
298 if (this.amountHint.getValue() == null)
300 amountHintIsSet = false;
303 if (amountHint.equals(this.amountHint.getValue()))
305 amountHintIsSet = true;
308 this.amountHint.setValue(amountHint);
310 void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
311 @NonNull androidx.lifecycle.Observer<? super String> observer) {
312 this.amountHint.observe(owner, observer);
314 void stopObservingAmountHint(
315 @NonNull androidx.lifecycle.Observer<? super String> observer) {
316 this.amountHint.removeObserver(observer);
321 void ensureType(ItemType wantedType) {
322 if (type != wantedType) {
323 throw new RuntimeException(
324 String.format("Actual type (%s) differs from wanted (%s)", type,
328 public Date getDate() {
329 ensureType(ItemType.generalData);
330 return date.getValue();
332 public void setDate(Date date) {
333 ensureType(ItemType.generalData);
334 this.date.setValue(date);
336 public void setDate(String text) {
337 if ((text == null) || text.trim()
340 setDate((Date) null);
344 int year, month, day;
345 final Calendar c = GregorianCalendar.getInstance();
346 Matcher m = reYMD.matcher(text);
348 year = Integer.parseInt(m.group(1));
349 month = Integer.parseInt(m.group(2)) - 1; // month is 0-based
350 day = Integer.parseInt(m.group(3));
353 year = c.get(Calendar.YEAR);
354 m = reMD.matcher(text);
356 month = Integer.parseInt(m.group(1)) - 1;
357 day = Integer.parseInt(m.group(2));
360 month = c.get(Calendar.MONTH);
361 m = reD.matcher(text);
363 day = Integer.parseInt(m.group(1));
366 day = c.get(Calendar.DAY_OF_MONTH);
371 c.set(year, month, day);
373 this.setDate(c.getTime());
375 void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
376 @NonNull androidx.lifecycle.Observer<? super Date> observer) {
377 this.date.observe(owner, observer);
379 void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
380 this.date.removeObserver(observer);
382 public String getDescription() {
383 ensureType(ItemType.generalData);
384 return description.getValue();
386 public void setDescription(String description) {
387 ensureType(ItemType.generalData);
388 this.description.setValue(description);
390 void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
391 @NonNull androidx.lifecycle.Observer<? super String> observer) {
392 this.description.observe(owner, observer);
394 void stopObservingDescription(
395 @NonNull androidx.lifecycle.Observer<? super String> observer) {
396 this.description.removeObserver(observer);
398 public String getTransactionComment() {
399 ensureType(ItemType.generalData);
400 return comment.getValue();
402 public void setTransactionComment(String transactionComment) {
403 ensureType(ItemType.generalData);
404 this.comment.setValue(transactionComment);
406 void observeTransactionComment(@NonNull @NotNull LifecycleOwner owner,
407 @NonNull Observer<? super String> observer) {
408 ensureType(ItemType.generalData);
409 this.comment.observe(owner, observer);
411 void stopObservingTransactionComment(@NonNull Observer<? super String> observer) {
412 this.comment.removeObserver(observer);
414 public LedgerTransactionAccount getAccount() {
415 ensureType(ItemType.transactionRow);
418 public void setAccountName(String name) {
419 account.setAccountName(name);
424 * @return nicely formatted, shortest available date representation
426 String getFormattedDate() {
429 Date time = date.getValue();
433 Calendar c = GregorianCalendar.getInstance();
435 Calendar today = GregorianCalendar.getInstance();
437 final int myYear = c.get(Calendar.YEAR);
438 final int myMonth = c.get(Calendar.MONTH);
439 final int myDay = c.get(Calendar.DAY_OF_MONTH);
441 if (today.get(Calendar.YEAR) != myYear) {
442 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth + 1, myDay);
445 if (today.get(Calendar.MONTH) != myMonth) {
446 return String.format(Locale.US, "%d/%02d", myMonth + 1, myDay);
449 return String.valueOf(myDay);
451 void observeEditableFlag(NewTransactionActivity activity, Observer<Boolean> observer) {
452 editable.observe(activity, observer);
454 void stopObservingEditableFlag(Observer<Boolean> observer) {
455 editable.removeObserver(observer);
457 void observeComment(NewTransactionActivity activity, Observer<String> observer) {
458 comment.observe(activity, observer);
460 void stopObservingComment(Observer<String> observer) {
461 comment.removeObserver(observer);
463 public void setComment(String comment) {
464 getAccount().setComment(comment);
465 this.comment.postValue(comment);
467 public Currency getCurrency() {
468 return this.currency.getValue();
470 public void setCurrency(Currency currency) {
471 Currency present = this.currency.getValue();
472 if ((currency == null) && (present != null) ||
473 (currency != null) && !currency.equals(present))
475 getAccount().setCurrency((currency != null && !currency.getName()
477 ? currency.getName() : null);
478 this.currency.setValue(currency);
481 void observeCurrency(NewTransactionActivity activity, Observer<Currency> observer) {
482 currency.observe(activity, observer);
484 void stopObservingCurrency(Observer<Currency> observer) {
485 currency.removeObserver(observer);
487 boolean isOfType(ItemType type) {
488 return this.type == type;
490 boolean isAmountHintSet() {
491 return amountHintIsSet;
493 void validateAmount() {
494 amountValid.setValue(true);
496 void invalidateAmount() {
497 amountValid.setValue(false);
499 void observeAmountValidity(NewTransactionActivity activity, Observer<Boolean> observer) {
500 amountValid.observe(activity, observer);
502 void stopObservingAmountValidity(Observer<Boolean> observer) {
503 amountValid.removeObserver(observer);