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.setLongOption(MLDB.OPT_PROFILE_ID, newProfile.getId());
98 profile.setValue(newProfile);
100 public static void postCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
101 MLDB.setLongOption(MLDB.OPT_PROFILE_ID, newProfile.getId());
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(long profileId) {
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);
126 if (p.getId() == profileId)
133 public static int retrieveCurrentThemeIdFromDb() {
134 long profileId = MLDB.getLongOption(MLDB.OPT_PROFILE_ID, 0);
138 SQLiteDatabase db = App.getDatabase();
139 try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
140 new String[]{String.valueOf(profileId)}))
149 public static MobileLedgerProfile getProfile(long profileId) {
150 MobileLedgerProfile profile;
151 try (LockHolder readLock = profilesLocker.lockForReading()) {
152 List<MobileLedgerProfile> prList = profiles.getValue();
153 if ((prList == null) || prList.isEmpty()) {
155 try (LockHolder ignored = profilesLocker.lockForWriting()) {
156 profile = MobileLedgerProfile.loadAllFromDB(profileId);
160 int i = getProfileIndex(profileId);
163 profile = prList.get(i);
168 public static void refreshCurrencyData(Locale locale) {
169 NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
170 java.util.Currency currency = formatter.getCurrency();
171 String symbol = currency != null ? currency.getSymbol() : "";
172 Logger.debug("locale", String.format(
173 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
174 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
175 String formatted = formatter.format(1234.56f);
176 Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
178 if (formatted.startsWith(symbol)) {
179 currencySymbolPosition.setValue(Currency.Position.before);
181 // is the currency symbol directly followed by the first formatted digit?
182 final char canary = formatted.charAt(symbol.length());
183 currencyGap.setValue(canary != '1');
185 else if (formatted.endsWith(symbol)) {
186 currencySymbolPosition.setValue(Currency.Position.after);
188 // is the currency symbol directly preceded bu the last formatted digit?
189 final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
190 currencyGap.setValue(canary != '6');
193 currencySymbolPosition.setValue(Currency.Position.none);
195 NumberFormat newNumberFormatter = NumberFormat.getNumberInstance();
196 newNumberFormatter.setParseIntegerOnly(false);
197 newNumberFormatter.setGroupingUsed(true);
198 newNumberFormatter.setGroupingUsed(true);
199 newNumberFormatter.setMinimumIntegerDigits(1);
200 newNumberFormatter.setMinimumFractionDigits(2);
202 numberFormatter = newNumberFormatter;
204 public static String formatCurrency(float number) {
205 NumberFormat formatter = NumberFormat.getCurrencyInstance(locale.getValue());
206 return formatter.format(number);
208 public static String formatNumber(float number) {
209 return numberFormatter.format(number);
211 public static void observeProfile(LifecycleOwner lifecycleOwner,
212 Observer<MobileLedgerProfile> observer) {
213 profile.observe(lifecycleOwner, observer);
215 public synchronized static MobileLedgerProfile initProfile() {
216 MobileLedgerProfile currentProfile = profile.getValue();
217 if (currentProfile != null)
218 return currentProfile;
220 long profileId = MLDB.getLongOption(MLDB.OPT_PROFILE_ID, 0);
221 MobileLedgerProfile startupProfile = getProfile(profileId);
222 if (startupProfile != null)
223 setCurrentProfile(startupProfile);
224 Logger.debug("profile", "initProfile() returning " + startupProfile);
225 return startupProfile;
228 public static void removeProfileObservers(LifecycleOwner owner) {
229 profile.removeObservers(owner);
231 public static float parseNumber(String str) throws ParseException {
232 ParsePosition pos = new ParsePosition(0);
233 Number parsed = numberFormatter.parse(str);
234 if (parsed == null || pos.getErrorIndex() > -1)
235 throw new ParseException("Error parsing '" + str + "'", pos.getErrorIndex());
237 return parsed.floatValue();