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 LiveData<Boolean> isSubmittable() {
97 return this.isSubmittable;
100 header.date.setValue(null);
101 header.description.setValue(null);
103 items.add(new Item(this, new LedgerTransactionAccount("")));
104 items.add(new Item(this, new LedgerTransactionAccount("")));
105 focusedItem.setValue(0);
107 void observeFocusedItem(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
108 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
109 this.focusedItem.observe(owner, observer);
111 void stopObservingFocusedItem(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
112 this.focusedItem.removeObserver(observer);
114 void observeAccountCount(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
115 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
116 this.accountCount.observe(owner, observer);
118 void stopObservingAccountCount(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
119 this.accountCount.removeObserver(observer);
121 int getFocusedItem() { return focusedItem.getValue(); }
122 void setFocusedItem(int position) {
123 focusedItem.setValue(position);
125 int addAccount(LedgerTransactionAccount acc) {
126 items.add(new Item(this, acc));
127 accountCount.setValue(getAccountCount());
130 boolean accountsInInitialState() {
131 for (Item item : items) {
132 LedgerTransactionAccount acc = item.getAccount();
133 if (acc.isAmountSet())
135 if (!acc.getAccountName()
143 LedgerTransactionAccount getAccount(int index) {
144 return items.get(index)
147 Item getItem(int index) {
152 if (index <= items.size())
153 return items.get(index - 1);
157 void removeRow(Item item, NewTransactionItemsAdapter adapter) {
158 int pos = items.indexOf(item);
160 if (adapter != null) {
161 adapter.notifyItemRemoved(pos + 1);
162 sendCountNotifications();
165 void removeItem(int pos) {
167 accountCount.setValue(getAccountCount());
169 void sendCountNotifications() {
170 accountCount.setValue(getAccountCount());
172 public void sendFocusedNotification() {
173 focusedItem.setValue(focusedItem.getValue());
175 void updateFocusedItem(int position) {
176 focusedItem.setValue(position);
178 void noteFocusChanged(int position, FocusedElement element) {
179 getItem(position).setFocusedElement(element);
181 void swapItems(int one, int two) {
182 Collections.swap(items, one - 1, two - 1);
184 void moveItemLast(int index) {
188 3 <-- desired position
190 int itemCount = items.size();
192 if (index < itemCount - 1) {
193 Item acc = items.remove(index);
194 items.add(itemCount - 1, acc);
197 void toggleCurrencyVisible() {
198 showCurrency.setValue(!showCurrency.getValue());
200 void stopObservingBusyFlag(Observer<Boolean> observer) {
201 busyFlag.removeObserver(observer);
203 void incrementBusyCounter() {
204 int newValue = busyCounter.incrementAndGet();
205 if (newValue == 1) busyFlag.postValue(true);
207 void decrementBusyCounter() {
208 int newValue = busyCounter.decrementAndGet();
209 if (newValue == 0) busyFlag.postValue(false);
211 public boolean getBusyFlag() {
212 return busyFlag.getValue();
214 public void toggleShowComments() {
215 showComments.setValue(!showComments.getValue());
217 enum ItemType {generalData, transactionRow, bottomFiller}
219 enum FocusedElement {Account, Comment, Amount}
222 //==========================================================================================
226 private ItemType type;
227 private MutableLiveData<Date> date = new MutableLiveData<>();
228 private MutableLiveData<String> description = new MutableLiveData<>();
229 private LedgerTransactionAccount account;
230 private MutableLiveData<String> amountHint = new MutableLiveData<>(null);
231 private NewTransactionModel model;
232 private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
233 private FocusedElement focusedElement = FocusedElement.Account;
234 private MutableLiveData<String> comment = new MutableLiveData<>(null);
235 private MutableLiveData<Currency> currency = new MutableLiveData<>(null);
236 private boolean amountHintIsSet = false;
237 Item(NewTransactionModel model) {
239 type = ItemType.bottomFiller;
240 editable.setValue(false);
242 Item(NewTransactionModel model, Date date, String description) {
244 this.type = ItemType.generalData;
245 this.date.setValue(date);
246 this.description.setValue(description);
247 this.editable.setValue(true);
249 Item(NewTransactionModel model, LedgerTransactionAccount account) {
251 this.type = ItemType.transactionRow;
252 this.account = account;
253 String currName = account.getCurrency();
254 Currency curr = null;
255 if ((currName != null) && !currName.isEmpty())
256 curr = Currency.loadByName(currName);
257 this.currency.setValue(curr);
258 this.editable.setValue(true);
260 FocusedElement getFocusedElement() {
261 return focusedElement;
263 void setFocusedElement(FocusedElement focusedElement) {
264 this.focusedElement = focusedElement;
266 public NewTransactionModel getModel() {
269 void setEditable(boolean editable) {
270 ensureType(ItemType.generalData, ItemType.transactionRow);
271 this.editable.setValue(editable);
273 private void ensureType(ItemType type1, ItemType type2) {
274 if ((type != type1) && (type != type2)) {
275 throw new RuntimeException(
276 String.format("Actual type (%s) differs from wanted (%s or %s)", type,
280 String getAmountHint() {
281 ensureType(ItemType.transactionRow);
282 return amountHint.getValue();
284 void setAmountHint(String amountHint) {
285 ensureType(ItemType.transactionRow);
287 // avoid unnecessary triggers
288 if (amountHint == null) {
289 if (this.amountHint.getValue() == null)
291 amountHintIsSet = false;
294 if (amountHint.equals(this.amountHint.getValue()))
296 amountHintIsSet = true;
299 this.amountHint.setValue(amountHint);
301 void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
302 @NonNull androidx.lifecycle.Observer<? super String> observer) {
303 this.amountHint.observe(owner, observer);
305 void stopObservingAmountHint(
306 @NonNull androidx.lifecycle.Observer<? super String> observer) {
307 this.amountHint.removeObserver(observer);
312 void ensureType(ItemType wantedType) {
313 if (type != wantedType) {
314 throw new RuntimeException(
315 String.format("Actual type (%s) differs from wanted (%s)", type,
319 public Date getDate() {
320 ensureType(ItemType.generalData);
321 return date.getValue();
323 public void setDate(Date date) {
324 ensureType(ItemType.generalData);
325 this.date.setValue(date);
327 public void setDate(String text) {
328 if ((text == null) || text.trim()
331 setDate((Date) null);
335 int year, month, day;
336 final Calendar c = GregorianCalendar.getInstance();
337 Matcher m = reYMD.matcher(text);
339 year = Integer.parseInt(m.group(1));
340 month = Integer.parseInt(m.group(2)) - 1; // month is 0-based
341 day = Integer.parseInt(m.group(3));
344 year = c.get(Calendar.YEAR);
345 m = reMD.matcher(text);
347 month = Integer.parseInt(m.group(1)) - 1;
348 day = Integer.parseInt(m.group(2));
351 month = c.get(Calendar.MONTH);
352 m = reD.matcher(text);
354 day = Integer.parseInt(m.group(1));
357 day = c.get(Calendar.DAY_OF_MONTH);
362 c.set(year, month, day);
364 this.setDate(c.getTime());
366 void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
367 @NonNull androidx.lifecycle.Observer<? super Date> observer) {
368 this.date.observe(owner, observer);
370 void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
371 this.date.removeObserver(observer);
373 public String getDescription() {
374 ensureType(ItemType.generalData);
375 return description.getValue();
377 public void setDescription(String description) {
378 ensureType(ItemType.generalData);
379 this.description.setValue(description);
381 void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
382 @NonNull androidx.lifecycle.Observer<? super String> observer) {
383 this.description.observe(owner, observer);
385 void stopObservingDescription(
386 @NonNull androidx.lifecycle.Observer<? super String> observer) {
387 this.description.removeObserver(observer);
389 public LedgerTransactionAccount getAccount() {
390 ensureType(ItemType.transactionRow);
393 public void setAccountName(String name) {
394 account.setAccountName(name);
399 * @return nicely formatted, shortest available date representation
401 String getFormattedDate() {
404 Date time = date.getValue();
408 Calendar c = GregorianCalendar.getInstance();
410 Calendar today = GregorianCalendar.getInstance();
412 final int myYear = c.get(Calendar.YEAR);
413 final int myMonth = c.get(Calendar.MONTH);
414 final int myDay = c.get(Calendar.DAY_OF_MONTH);
416 if (today.get(Calendar.YEAR) != myYear) {
417 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth + 1, myDay);
420 if (today.get(Calendar.MONTH) != myMonth) {
421 return String.format(Locale.US, "%d/%02d", myMonth + 1, myDay);
424 return String.valueOf(myDay);
426 void observeEditableFlag(NewTransactionActivity activity, Observer<Boolean> observer) {
427 editable.observe(activity, observer);
429 void stopObservingEditableFlag(Observer<Boolean> observer) {
430 editable.removeObserver(observer);
432 void observeComment(NewTransactionActivity activity, Observer<String> observer) {
433 comment.observe(activity, observer);
435 void stopObservingComment(Observer<String> observer) {
436 comment.removeObserver(observer);
438 public void setComment(String comment) {
439 getAccount().setComment(comment);
440 this.comment.postValue(comment);
442 public Currency getCurrency() {
443 return this.currency.getValue();
445 public void setCurrency(Currency currency) {
446 Currency present = this.currency.getValue();
447 if ((currency == null) && (present != null) ||
448 (currency != null) && !currency.equals(present))
450 getAccount().setCurrency((currency != null && !currency.getName()
452 ? currency.getName() : null);
453 this.currency.setValue(currency);
456 void observeCurrency(NewTransactionActivity activity, Observer<Currency> observer) {
457 currency.observe(activity, observer);
459 void stopObservingCurrency(Observer<Currency> observer) {
460 currency.removeObserver(observer);
462 boolean isOfType(ItemType type) {
463 return this.type == type;
465 boolean isAmountHintSet() {
466 return amountHintIsSet;