]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
make decimal separator available globally
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / Data.java
1 /*
2  * Copyright © 2021 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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.model;
19
20 import androidx.annotation.NonNull;
21 import androidx.annotation.Nullable;
22 import androidx.lifecycle.LifecycleOwner;
23 import androidx.lifecycle.LiveData;
24 import androidx.lifecycle.MutableLiveData;
25 import androidx.lifecycle.Observer;
26
27 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
28 import net.ktnx.mobileledger.db.DB;
29 import net.ktnx.mobileledger.db.Profile;
30 import net.ktnx.mobileledger.utils.Locker;
31 import net.ktnx.mobileledger.utils.Logger;
32
33 import org.jetbrains.annotations.NotNull;
34
35 import java.text.DecimalFormatSymbols;
36 import java.text.NumberFormat;
37 import java.text.ParseException;
38 import java.text.ParsePosition;
39 import java.util.Date;
40 import java.util.List;
41 import java.util.Locale;
42 import java.util.concurrent.atomic.AtomicInteger;
43
44 import static net.ktnx.mobileledger.utils.Logger.debug;
45
46 public final class Data {
47     public static final MutableLiveData<Boolean> backgroundTasksRunning =
48             new MutableLiveData<>(false);
49     public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
50             new MutableLiveData<>();
51     public static final LiveData<List<Profile>> profiles = DB.get()
52                                                              .getProfileDAO()
53                                                              .getAllOrdered();
54     public static final MutableLiveData<Currency.Position> currencySymbolPosition =
55             new MutableLiveData<>();
56     public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
57     public static final MutableLiveData<Locale> locale = new MutableLiveData<>();
58     public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
59     public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>(null);
60     public static final MutableLiveData<Integer> lastUpdateTransactionCount =
61             new MutableLiveData<>(0);
62     public static final MutableLiveData<Integer> lastUpdateAccountCount = new MutableLiveData<>(0);
63     public static final MutableLiveData<String> lastTransactionsUpdateText =
64             new MutableLiveData<>();
65     public static final MutableLiveData<String> lastAccountsUpdateText = new MutableLiveData<>();
66     public static final String decimalDot = ".";
67
68     private static final MutableLiveData<Profile> profile = new MutableLiveData<>();
69     private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
70     private static final Locker profilesLocker = new Locker();
71     private static NumberFormat numberFormatter;
72     private static String decimalSeparator = "";
73
74     static {
75         locale.setValue(Locale.getDefault());
76     }
77
78     public static String getDecimalSeparator() {
79         return decimalSeparator;
80     }
81     @Nullable
82     public static Profile getProfile() {
83         return profile.getValue();
84     }
85     public static void backgroundTaskStarted() {
86         int cnt = backgroundTaskCount.incrementAndGet();
87         debug("data",
88                 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
89                         cnt));
90         backgroundTasksRunning.postValue(cnt > 0);
91     }
92     public static void backgroundTaskFinished() {
93         int cnt = backgroundTaskCount.decrementAndGet();
94         debug("data",
95                 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
96                         cnt));
97         backgroundTasksRunning.postValue(cnt > 0);
98     }
99     public static void setCurrentProfile(@NonNull Profile newProfile) {
100         profile.setValue(newProfile);
101     }
102     public static void postCurrentProfile(@NonNull Profile newProfile) {
103         profile.postValue(newProfile);
104     }
105     public static void refreshCurrencyData(Locale locale) {
106         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
107         java.util.Currency currency = formatter.getCurrency();
108         String symbol = currency != null ? currency.getSymbol() : "";
109         Logger.debug("locale", String.format(
110                 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
111                 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
112         String formatted = formatter.format(1234.56f);
113         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
114
115         if (formatted.startsWith(symbol)) {
116             currencySymbolPosition.setValue(Currency.Position.before);
117
118             // is the currency symbol directly followed by the first formatted digit?
119             final char canary = formatted.charAt(symbol.length());
120             currencyGap.setValue(canary != '1');
121         }
122         else if (formatted.endsWith(symbol)) {
123             currencySymbolPosition.setValue(Currency.Position.after);
124
125             // is the currency symbol directly preceded bu the last formatted digit?
126             final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
127             currencyGap.setValue(canary != '6');
128         }
129         else
130             currencySymbolPosition.setValue(Currency.Position.none);
131
132         NumberFormat newNumberFormatter = NumberFormat.getNumberInstance();
133         newNumberFormatter.setParseIntegerOnly(false);
134         newNumberFormatter.setGroupingUsed(true);
135         newNumberFormatter.setMinimumIntegerDigits(1);
136         newNumberFormatter.setMinimumFractionDigits(2);
137
138         numberFormatter = newNumberFormatter;
139
140         decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance(locale)
141                                                               .getMonetaryDecimalSeparator());
142     }
143     @NotNull
144     public static String formatCurrency(float number) {
145         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale.getValue());
146         return formatter.format(number);
147     }
148     @NotNull
149     public static String formatNumber(float number) {
150         return numberFormatter.format(number);
151     }
152     public static void observeProfile(LifecycleOwner lifecycleOwner, Observer<Profile> observer) {
153         profile.observe(lifecycleOwner, observer);
154     }
155     public static void removeProfileObservers(LifecycleOwner owner) {
156         profile.removeObservers(owner);
157     }
158     public static float parseNumber(String str) throws ParseException {
159         ParsePosition pos = new ParsePosition(0);
160         Number parsed = numberFormatter.parse(str);
161         if (parsed == null || pos.getErrorIndex() > -1)
162             throw new ParseException("Error parsing '" + str + "'", pos.getErrorIndex());
163
164         return parsed.floatValue();
165     }
166 }