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(@NonNull 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 public boolean getBusyFlag() {
208 return busyFlag.getValue();
210 enum ItemType {generalData, transactionRow, bottomFiller}
212 enum FocusedElement {Account, Comment, Amount}
215 //==========================================================================================
219 private ItemType type;
220 private MutableLiveData<Date> date = new MutableLiveData<>();
221 private MutableLiveData<String> description = new MutableLiveData<>();
222 private LedgerTransactionAccount account;
223 private MutableLiveData<String> amountHint = new MutableLiveData<>(null);
224 private NewTransactionModel model;
225 private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
226 private FocusedElement focusedElement = FocusedElement.Account;
227 private MutableLiveData<String> comment = new MutableLiveData<>(null);
228 private MutableLiveData<Currency> currency = new MutableLiveData<>(null);
229 private boolean amountHintIsSet = false;
230 Item(NewTransactionModel model) {
232 type = ItemType.bottomFiller;
233 editable.setValue(false);
235 Item(NewTransactionModel model, Date date, String description) {
237 this.type = ItemType.generalData;
238 this.date.setValue(date);
239 this.description.setValue(description);
240 this.editable.setValue(true);
242 Item(NewTransactionModel model, LedgerTransactionAccount account) {
244 this.type = ItemType.transactionRow;
245 this.account = account;
246 String currName = account.getCurrency();
247 Currency curr = null;
248 if ((currName != null) && !currName.isEmpty())
249 curr = Currency.loadByName(currName);
250 this.currency.setValue(curr);
251 this.editable.setValue(true);
253 FocusedElement getFocusedElement() {
254 return focusedElement;
256 void setFocusedElement(FocusedElement focusedElement) {
257 this.focusedElement = focusedElement;
259 public NewTransactionModel getModel() {
262 void setEditable(boolean editable) {
263 ensureType(ItemType.generalData, ItemType.transactionRow);
264 this.editable.setValue(editable);
266 private void ensureType(ItemType type1, ItemType type2) {
267 if ((type != type1) && (type != type2)) {
268 throw new RuntimeException(
269 String.format("Actual type (%s) differs from wanted (%s or %s)", type,
273 String getAmountHint() {
274 ensureType(ItemType.transactionRow);
275 return amountHint.getValue();
277 void setAmountHint(String amountHint) {
278 ensureType(ItemType.transactionRow);
280 // avoid unnecessary triggers
281 if (amountHint == null) {
282 if (this.amountHint.getValue() == null)
284 amountHintIsSet = false;
287 if (amountHint.equals(this.amountHint.getValue()))
289 amountHintIsSet = true;
292 this.amountHint.setValue(amountHint);
294 void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
295 @NonNull androidx.lifecycle.Observer<? super String> observer) {
296 this.amountHint.observe(owner, observer);
298 void stopObservingAmountHint(
299 @NonNull androidx.lifecycle.Observer<? super String> observer) {
300 this.amountHint.removeObserver(observer);
305 void ensureType(ItemType wantedType) {
306 if (type != wantedType) {
307 throw new RuntimeException(
308 String.format("Actual type (%s) differs from wanted (%s)", type,
312 public Date getDate() {
313 ensureType(ItemType.generalData);
314 return date.getValue();
316 public void setDate(Date date) {
317 ensureType(ItemType.generalData);
318 this.date.setValue(date);
320 public void setDate(String text) {
321 if ((text == null) || text.trim()
324 setDate((Date) null);
328 int year, month, day;
329 final Calendar c = GregorianCalendar.getInstance();
330 Matcher m = reYMD.matcher(text);
332 year = Integer.parseInt(m.group(1));
333 month = Integer.parseInt(m.group(2)) - 1; // month is 0-based
334 day = Integer.parseInt(m.group(3));
337 year = c.get(Calendar.YEAR);
338 m = reMD.matcher(text);
340 month = Integer.parseInt(m.group(1)) - 1;
341 day = Integer.parseInt(m.group(2));
344 month = c.get(Calendar.MONTH);
345 m = reD.matcher(text);
347 day = Integer.parseInt(m.group(1));
350 day = c.get(Calendar.DAY_OF_MONTH);
355 c.set(year, month, day);
357 this.setDate(c.getTime());
359 void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
360 @NonNull androidx.lifecycle.Observer<? super Date> observer) {
361 this.date.observe(owner, observer);
363 void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
364 this.date.removeObserver(observer);
366 public String getDescription() {
367 ensureType(ItemType.generalData);
368 return description.getValue();
370 public void setDescription(String description) {
371 ensureType(ItemType.generalData);
372 this.description.setValue(description);
374 void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
375 @NonNull androidx.lifecycle.Observer<? super String> observer) {
376 this.description.observe(owner, observer);
378 void stopObservingDescription(
379 @NonNull androidx.lifecycle.Observer<? super String> observer) {
380 this.description.removeObserver(observer);
382 public LedgerTransactionAccount getAccount() {
383 ensureType(ItemType.transactionRow);
386 public void setAccountName(String name) {
387 account.setAccountName(name);
392 * @return nicely formatted, shortest available date representation
394 String getFormattedDate() {
397 Date time = date.getValue();
401 Calendar c = GregorianCalendar.getInstance();
403 Calendar today = GregorianCalendar.getInstance();
405 final int myYear = c.get(Calendar.YEAR);
406 final int myMonth = c.get(Calendar.MONTH);
407 final int myDay = c.get(Calendar.DAY_OF_MONTH);
409 if (today.get(Calendar.YEAR) != myYear) {
410 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth + 1, myDay);
413 if (today.get(Calendar.MONTH) != myMonth) {
414 return String.format(Locale.US, "%d/%02d", myMonth + 1, myDay);
417 return String.valueOf(myDay);
419 void observeEditableFlag(NewTransactionActivity activity, Observer<Boolean> observer) {
420 editable.observe(activity, observer);
422 void stopObservingEditableFlag(Observer<Boolean> observer) {
423 editable.removeObserver(observer);
425 void observeComment(NewTransactionActivity activity, Observer<String> observer) {
426 comment.observe(activity, observer);
428 void stopObservingComment(Observer<String> observer) {
429 comment.removeObserver(observer);
431 public void setComment(String comment) {
432 getAccount().setComment(comment);
433 this.comment.postValue(comment);
435 public Currency getCurrency() {
436 return this.currency.getValue();
438 public void setCurrency(Currency currency) {
439 Currency present = this.currency.getValue();
440 if ((currency == null) && (present != null) ||
441 (currency != null) && !currency.equals(present))
443 getAccount().setCurrency((currency != null && !currency.getName()
445 ? currency.getName() : null);
446 this.currency.setValue(currency);
449 void observeCurrency(NewTransactionActivity activity, Observer<Currency> observer) {
450 currency.observe(activity, observer);
452 void stopObservingCurrency(Observer<Currency> observer) {
453 currency.removeObserver(observer);
455 boolean isOfType(ItemType type) {
456 return this.type == type;
458 boolean isAmountHintSet() {
459 return amountHintIsSet;