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 void observeBusyFlag(LifecycleOwner owner, Observer<? super Boolean> observer) {
63 busyFlag.observe(owner, observer);
65 void observeDataProfile(LifecycleOwner activity) {
66 if (!observingDataProfile)
67 Data.profile.observe(activity, profileObserver);
68 observingDataProfile = true;
70 boolean getSimulateSave() {
71 return simulateSave.getValue();
73 public void setSimulateSave(boolean simulateSave) {
74 this.simulateSave.setValue(simulateSave);
76 void toggleSimulateSave() {
77 simulateSave.setValue(!simulateSave.getValue());
79 void observeSimulateSave(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
80 @NonNull androidx.lifecycle.Observer<? super Boolean> observer) {
81 this.simulateSave.observe(owner, observer);
83 int getAccountCount() {
86 public Date getDate() {
87 return header.date.getValue();
89 public String getDescription() {
90 return header.description.getValue();
92 LiveData<Boolean> isSubmittable() {
93 return this.isSubmittable;
96 header.date.setValue(null);
97 header.description.setValue(null);
99 items.add(new Item(this, new LedgerTransactionAccount("")));
100 items.add(new Item(this, new LedgerTransactionAccount("")));
101 focusedItem.setValue(0);
103 void observeFocusedItem(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
104 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
105 this.focusedItem.observe(owner, observer);
107 void stopObservingFocusedItem(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
108 this.focusedItem.removeObserver(observer);
110 void observeAccountCount(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
111 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
112 this.accountCount.observe(owner, observer);
114 void stopObservingAccountCount(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
115 this.accountCount.removeObserver(observer);
117 int getFocusedItem() { return focusedItem.getValue(); }
118 void setFocusedItem(int position) {
119 focusedItem.setValue(position);
121 int addAccount(LedgerTransactionAccount acc) {
122 items.add(new Item(this, acc));
123 accountCount.setValue(getAccountCount());
126 boolean accountsInInitialState() {
127 for (Item item : items) {
128 LedgerTransactionAccount acc = item.getAccount();
129 if (acc.isAmountSet())
131 if (!acc.getAccountName()
139 LedgerTransactionAccount getAccount(int index) {
140 return items.get(index)
143 Item getItem(int index) {
148 if (index <= items.size())
149 return items.get(index - 1);
153 void removeRow(Item item, NewTransactionItemsAdapter adapter) {
154 int pos = items.indexOf(item);
156 if (adapter != null) {
157 adapter.notifyItemRemoved(pos + 1);
158 sendCountNotifications();
161 void removeItem(int pos) {
163 accountCount.setValue(getAccountCount());
165 void sendCountNotifications() {
166 accountCount.setValue(getAccountCount());
168 public void sendFocusedNotification() {
169 focusedItem.setValue(focusedItem.getValue());
171 void updateFocusedItem(int position) {
172 focusedItem.setValue(position);
174 void noteFocusChanged(int position, FocusedElement element) {
175 getItem(position).setFocusedElement(element);
177 void swapItems(int one, int two) {
178 Collections.swap(items, one - 1, two - 1);
180 void moveItemLast(int index) {
184 3 <-- desired position
186 int itemCount = items.size();
188 if (index < itemCount - 1) {
189 Item acc = items.remove(index);
190 items.add(itemCount - 1, acc);
193 void toggleCurrencyVisible() {
194 showCurrency.setValue(!showCurrency.getValue());
196 void stopObservingBusyFlag(Observer<Boolean> observer) {
197 busyFlag.removeObserver(observer);
199 void incrementBusyCounter() {
200 int newValue = busyCounter.incrementAndGet();
201 if (newValue == 1) busyFlag.postValue(true);
203 void decrementBusyCounter() {
204 int newValue = busyCounter.decrementAndGet();
205 if (newValue == 0) busyFlag.postValue(false);
207 enum ItemType {generalData, transactionRow, bottomFiller}
209 enum FocusedElement {Account, Comment, Amount}
212 //==========================================================================================
216 private ItemType type;
217 private MutableLiveData<Date> date = new MutableLiveData<>();
218 private MutableLiveData<String> description = new MutableLiveData<>();
219 private LedgerTransactionAccount account;
220 private MutableLiveData<String> amountHint = new MutableLiveData<>(null);
221 private NewTransactionModel model;
222 private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
223 private FocusedElement focusedElement = FocusedElement.Account;
224 private MutableLiveData<String> comment = new MutableLiveData<>(null);
225 private MutableLiveData<Currency> currency = new MutableLiveData<>(null);
226 private boolean amountHintIsSet = false;
227 Item(NewTransactionModel model) {
229 type = ItemType.bottomFiller;
230 editable.setValue(false);
232 Item(NewTransactionModel model, Date date, String description) {
234 this.type = ItemType.generalData;
235 this.date.setValue(date);
236 this.description.setValue(description);
237 this.editable.setValue(true);
239 Item(NewTransactionModel model, LedgerTransactionAccount account) {
241 this.type = ItemType.transactionRow;
242 this.account = account;
243 String currName = account.getCurrency();
244 Currency curr = null;
245 if ((currName != null) && !currName.isEmpty())
246 curr = Currency.loadByName(currName);
247 this.currency.setValue(curr);
248 this.editable.setValue(true);
250 FocusedElement getFocusedElement() {
251 return focusedElement;
253 void setFocusedElement(FocusedElement focusedElement) {
254 this.focusedElement = focusedElement;
256 public NewTransactionModel getModel() {
259 void setEditable(boolean editable) {
260 ensureType(ItemType.generalData, ItemType.transactionRow);
261 this.editable.setValue(editable);
263 private void ensureType(ItemType type1, ItemType type2) {
264 if ((type != type1) && (type != type2)) {
265 throw new RuntimeException(
266 String.format("Actual type (%s) differs from wanted (%s or %s)", type,
270 String getAmountHint() {
271 ensureType(ItemType.transactionRow);
272 return amountHint.getValue();
274 void setAmountHint(String amountHint) {
275 ensureType(ItemType.transactionRow);
277 // avoid unnecessary triggers
278 if (amountHint == null) {
279 if (this.amountHint.getValue() == null)
281 amountHintIsSet = false;
284 if (amountHint.equals(this.amountHint.getValue()))
286 amountHintIsSet = true;
289 this.amountHint.setValue(amountHint);
291 void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
292 @NonNull androidx.lifecycle.Observer<? super String> observer) {
293 this.amountHint.observe(owner, observer);
295 void stopObservingAmountHint(
296 @NonNull androidx.lifecycle.Observer<? super String> observer) {
297 this.amountHint.removeObserver(observer);
302 void ensureType(ItemType wantedType) {
303 if (type != wantedType) {
304 throw new RuntimeException(
305 String.format("Actual type (%s) differs from wanted (%s)", type,
309 public Date getDate() {
310 ensureType(ItemType.generalData);
311 return date.getValue();
313 public void setDate(Date date) {
314 ensureType(ItemType.generalData);
315 this.date.setValue(date);
317 public void setDate(String text) {
318 if ((text == null) || text.trim()
321 setDate((Date) null);
325 int year, month, day;
326 final Calendar c = GregorianCalendar.getInstance();
327 Matcher m = reYMD.matcher(text);
329 year = Integer.parseInt(m.group(1));
330 month = Integer.parseInt(m.group(2)) - 1; // month is 0-based
331 day = Integer.parseInt(m.group(3));
334 year = c.get(Calendar.YEAR);
335 m = reMD.matcher(text);
337 month = Integer.parseInt(m.group(1)) - 1;
338 day = Integer.parseInt(m.group(2));
341 month = c.get(Calendar.MONTH);
342 m = reD.matcher(text);
344 day = Integer.parseInt(m.group(1));
347 day = c.get(Calendar.DAY_OF_MONTH);
352 c.set(year, month, day);
354 this.setDate(c.getTime());
356 void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
357 @NonNull androidx.lifecycle.Observer<? super Date> observer) {
358 this.date.observe(owner, observer);
360 void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
361 this.date.removeObserver(observer);
363 public String getDescription() {
364 ensureType(ItemType.generalData);
365 return description.getValue();
367 public void setDescription(String description) {
368 ensureType(ItemType.generalData);
369 this.description.setValue(description);
371 void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
372 @NonNull androidx.lifecycle.Observer<? super String> observer) {
373 this.description.observe(owner, observer);
375 void stopObservingDescription(
376 @NonNull androidx.lifecycle.Observer<? super String> observer) {
377 this.description.removeObserver(observer);
379 public LedgerTransactionAccount getAccount() {
380 ensureType(ItemType.transactionRow);
383 public void setAccountName(String name) {
384 account.setAccountName(name);
389 * @return nicely formatted, shortest available date representation
391 String getFormattedDate() {
394 Date time = date.getValue();
398 Calendar c = GregorianCalendar.getInstance();
400 Calendar today = GregorianCalendar.getInstance();
402 final int myYear = c.get(Calendar.YEAR);
403 final int myMonth = c.get(Calendar.MONTH);
404 final int myDay = c.get(Calendar.DAY_OF_MONTH);
406 if (today.get(Calendar.YEAR) != myYear) {
407 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth + 1, myDay);
410 if (today.get(Calendar.MONTH) != myMonth) {
411 return String.format(Locale.US, "%d/%02d", myMonth + 1, myDay);
414 return String.valueOf(myDay);
416 void observeEditableFlag(NewTransactionActivity activity, Observer<Boolean> observer) {
417 editable.observe(activity, observer);
419 void stopObservingEditableFlag(Observer<Boolean> observer) {
420 editable.removeObserver(observer);
422 void observeComment(NewTransactionActivity activity, Observer<String> observer) {
423 comment.observe(activity, observer);
425 void stopObservingComment(Observer<String> observer) {
426 comment.removeObserver(observer);
428 public void setComment(String comment) {
429 getAccount().setComment(comment);
430 this.comment.postValue(comment);
432 public Currency getCurrency() {
433 return this.currency.getValue();
435 public void setCurrency(Currency currency) {
436 Currency present = this.currency.getValue();
437 if ((currency == null) && (present != null) ||
438 (currency != null) && !currency.equals(present))
440 getAccount().setCurrency((currency != null && !currency.getName()
442 ? currency.getName() : null);
443 this.currency.setValue(currency);
446 void observeCurrency(NewTransactionActivity activity, Observer<Currency> observer) {
447 currency.observe(activity, observer);
449 void stopObservingCurrency(Observer<Currency> observer) {
450 currency.removeObserver(observer);
452 boolean isOfType(ItemType type) {
453 return this.type == type;
455 boolean isAmountHintSet() {
456 return amountHintIsSet;