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.
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.model;
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
23 import androidx.annotation.NonNull;
24 import androidx.annotation.Nullable;
25 import androidx.lifecycle.LifecycleOwner;
26 import androidx.lifecycle.MutableLiveData;
27 import androidx.lifecycle.Observer;
29 import net.ktnx.mobileledger.App;
30 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
31 import net.ktnx.mobileledger.utils.LockHolder;
32 import net.ktnx.mobileledger.utils.Locker;
33 import net.ktnx.mobileledger.utils.Logger;
34 import net.ktnx.mobileledger.utils.MLDB;
35 import net.ktnx.mobileledger.utils.ObservableValue;
37 import java.text.NumberFormat;
38 import java.text.ParseException;
39 import java.text.ParsePosition;
40 import java.util.ArrayList;
41 import java.util.Date;
42 import java.util.List;
43 import java.util.Locale;
44 import java.util.Objects;
45 import java.util.concurrent.atomic.AtomicInteger;
47 import static net.ktnx.mobileledger.utils.Logger.debug;
49 public final class Data {
50 public static final MutableLiveData<Boolean> backgroundTasksRunning =
51 new MutableLiveData<>(false);
52 public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
53 new MutableLiveData<>();
54 public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
55 new MutableLiveData<>(null);
56 public static final MutableLiveData<Currency.Position> currencySymbolPosition =
57 new MutableLiveData<>();
58 public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
59 public static final MutableLiveData<Locale> locale = new MutableLiveData<>();
60 public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
61 public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>(null);
62 public static final MutableLiveData<Integer> lastUpdateTransactionCount =
63 new MutableLiveData<>(0);
64 public static final MutableLiveData<Integer> lastUpdateAccountCount = new MutableLiveData<>(0);
65 public static final ObservableValue<String> lastTransactionsUpdateText =
66 new ObservableValue<>();
67 public static final ObservableValue<String> lastAccountsUpdateText = new ObservableValue<>();
68 private static final MutableLiveData<MobileLedgerProfile> profile =
69 new InertMutableLiveData<>();
70 private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
71 private static final Locker profilesLocker = new Locker();
72 private static NumberFormat numberFormatter;
75 locale.setValue(Locale.getDefault());
79 public static MobileLedgerProfile getProfile() {
80 return Objects.requireNonNull(profile.getValue());
82 public static void backgroundTaskStarted() {
83 int cnt = backgroundTaskCount.incrementAndGet();
85 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
87 backgroundTasksRunning.postValue(cnt > 0);
89 public static void backgroundTaskFinished() {
90 int cnt = backgroundTaskCount.decrementAndGet();
92 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
94 backgroundTasksRunning.postValue(cnt > 0);
96 public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
97 MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
98 profile.setValue(newProfile);
100 public static void postCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
101 MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
102 profile.postValue(newProfile);
104 public static int getProfileIndex(MobileLedgerProfile profile) {
105 try (LockHolder ignored = profilesLocker.lockForReading()) {
106 List<MobileLedgerProfile> prList = profiles.getValue();
108 throw new AssertionError();
109 for (int i = 0; i < prList.size(); i++) {
110 MobileLedgerProfile p = prList.get(i);
111 if (p.equals(profile))
118 @SuppressWarnings("WeakerAccess")
119 public static int getProfileIndex(String profileUUID) {
120 try (LockHolder ignored = profilesLocker.lockForReading()) {
121 List<MobileLedgerProfile> prList = profiles.getValue();
123 throw new AssertionError();
124 for (int i = 0; i < prList.size(); i++) {
125 MobileLedgerProfile p = prList.get(i);
127 .equals(profileUUID))
134 public static int retrieveCurrentThemeIdFromDb() {
135 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
136 if (profileUUID == null)
139 SQLiteDatabase db = App.getDatabase();
140 try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
141 new String[]{profileUUID}))
150 public static MobileLedgerProfile getProfile(String profileUUID) {
151 MobileLedgerProfile profile;
152 try (LockHolder readLock = profilesLocker.lockForReading()) {
153 List<MobileLedgerProfile> prList = profiles.getValue();
154 if ((prList == null) || prList.isEmpty()) {
156 try (LockHolder ignored = profilesLocker.lockForWriting()) {
157 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
161 int i = getProfileIndex(profileUUID);
164 profile = prList.get(i);
169 public static void refreshCurrencyData(Locale locale) {
170 NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
171 java.util.Currency currency = formatter.getCurrency();
172 String symbol = currency != null ? currency.getSymbol() : "";
173 Logger.debug("locale", String.format(
174 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
175 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
176 String formatted = formatter.format(1234.56f);
177 Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
179 if (formatted.startsWith(symbol)) {
180 currencySymbolPosition.setValue(Currency.Position.before);
182 // is the currency symbol directly followed by the first formatted digit?
183 final char canary = formatted.charAt(symbol.length());
184 currencyGap.setValue(canary != '1');
186 else if (formatted.endsWith(symbol)) {
187 currencySymbolPosition.setValue(Currency.Position.after);
189 // is the currency symbol directly preceded bu the last formatted digit?
190 final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
191 currencyGap.setValue(canary != '6');
194 currencySymbolPosition.setValue(Currency.Position.none);
196 NumberFormat newNumberFormatter = NumberFormat.getNumberInstance();
197 newNumberFormatter.setParseIntegerOnly(false);
198 newNumberFormatter.setGroupingUsed(true);
199 newNumberFormatter.setGroupingUsed(true);
200 newNumberFormatter.setMinimumIntegerDigits(1);
201 newNumberFormatter.setMinimumFractionDigits(2);
203 numberFormatter = newNumberFormatter;
205 public static String formatCurrency(float number) {
206 NumberFormat formatter = NumberFormat.getCurrencyInstance(locale.getValue());
207 return formatter.format(number);
209 public static String formatNumber(float number) {
210 return numberFormatter.format(number);
212 public static void observeProfile(LifecycleOwner lifecycleOwner,
213 Observer<MobileLedgerProfile> observer) {
214 profile.observe(lifecycleOwner, observer);
216 public synchronized static MobileLedgerProfile initProfile() {
217 MobileLedgerProfile currentProfile = profile.getValue();
218 if (currentProfile != null)
219 return currentProfile;
221 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
222 MobileLedgerProfile startupProfile = getProfile(profileUUID);
223 if (startupProfile != null)
224 setCurrentProfile(startupProfile);
225 Logger.debug("profile", "initProfile() returning " + startupProfile);
226 return startupProfile;
229 public static void removeProfileObservers(LifecycleOwner owner) {
230 profile.removeObservers(owner);
232 public static float parseNumber(String str) throws ParseException {
233 ParsePosition pos = new ParsePosition(0);
234 Number parsed = numberFormatter.parse(str);
235 if (parsed == null || pos.getErrorIndex() > -1)
236 throw new ParseException("Error parsing '" + str + "'", pos.getErrorIndex());
238 return parsed.floatValue();