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;
36 import java.text.NumberFormat;
37 import java.text.ParseException;
38 import java.text.ParsePosition;
39 import java.util.ArrayList;
40 import java.util.Date;
41 import java.util.List;
42 import java.util.Locale;
43 import java.util.Objects;
44 import java.util.concurrent.atomic.AtomicInteger;
46 import static net.ktnx.mobileledger.utils.Logger.debug;
48 public final class Data {
49 public static final MutableLiveData<Boolean> backgroundTasksRunning =
50 new MutableLiveData<>(false);
51 public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
52 new MutableLiveData<>();
53 public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
54 new MutableLiveData<>(null);
55 public static final MutableLiveData<Currency.Position> currencySymbolPosition =
56 new MutableLiveData<>();
57 public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
58 public static final MutableLiveData<Locale> locale = new MutableLiveData<>();
59 public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
60 public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>(null);
61 public static final MutableLiveData<Integer> lastUpdateTransactionCount =
62 new MutableLiveData<>(0);
63 public static final MutableLiveData<Integer> lastUpdateAccountCount = new MutableLiveData<>(0);
64 public static final MutableLiveData<String> lastTransactionsUpdateText =
65 new MutableLiveData<>();
66 public static final MutableLiveData<String> lastAccountsUpdateText = new MutableLiveData<>();
67 private static final MutableLiveData<MobileLedgerProfile> profile =
68 new InertMutableLiveData<>();
69 private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
70 private static final Locker profilesLocker = new Locker();
71 private static NumberFormat numberFormatter;
74 locale.setValue(Locale.getDefault());
78 public static MobileLedgerProfile getProfile() {
79 return Objects.requireNonNull(profile.getValue());
81 public static void backgroundTaskStarted() {
82 int cnt = backgroundTaskCount.incrementAndGet();
84 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
86 backgroundTasksRunning.postValue(cnt > 0);
88 public static void backgroundTaskFinished() {
89 int cnt = backgroundTaskCount.decrementAndGet();
91 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
93 backgroundTasksRunning.postValue(cnt > 0);
95 public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
96 MLDB.setLongOption(MLDB.OPT_PROFILE_ID, newProfile.getId());
97 profile.setValue(newProfile);
99 public static void postCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
100 MLDB.setLongOption(MLDB.OPT_PROFILE_ID, newProfile.getId());
101 profile.postValue(newProfile);
103 public static int getProfileIndex(MobileLedgerProfile profile) {
104 try (LockHolder ignored = profilesLocker.lockForReading()) {
105 List<MobileLedgerProfile> prList = profiles.getValue();
107 throw new AssertionError();
108 for (int i = 0; i < prList.size(); i++) {
109 MobileLedgerProfile p = prList.get(i);
110 if (p.equals(profile))
117 @SuppressWarnings("WeakerAccess")
118 public static int getProfileIndex(long profileId) {
119 try (LockHolder ignored = profilesLocker.lockForReading()) {
120 List<MobileLedgerProfile> prList = profiles.getValue();
122 throw new AssertionError();
123 for (int i = 0; i < prList.size(); i++) {
124 MobileLedgerProfile p = prList.get(i);
125 if (p.getId() == profileId)
132 public static int retrieveCurrentThemeIdFromDb() {
133 long profileId = MLDB.getLongOption(MLDB.OPT_PROFILE_ID, 0);
137 SQLiteDatabase db = App.getDatabase();
138 try (Cursor c = db.rawQuery("SELECT theme from profiles where id=?",
139 new String[]{String.valueOf(profileId)}))
148 public static MobileLedgerProfile getProfile(long profileId) {
149 MobileLedgerProfile profile;
150 try (LockHolder readLock = profilesLocker.lockForReading()) {
151 List<MobileLedgerProfile> prList = profiles.getValue();
152 if ((prList == null) || prList.isEmpty()) {
154 try (LockHolder ignored = profilesLocker.lockForWriting()) {
155 profile = MobileLedgerProfile.loadAllFromDB(profileId);
159 int i = getProfileIndex(profileId);
162 profile = prList.get(i);
167 public static void refreshCurrencyData(Locale locale) {
168 NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
169 java.util.Currency currency = formatter.getCurrency();
170 String symbol = currency != null ? currency.getSymbol() : "";
171 Logger.debug("locale", String.format(
172 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
173 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
174 String formatted = formatter.format(1234.56f);
175 Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
177 if (formatted.startsWith(symbol)) {
178 currencySymbolPosition.setValue(Currency.Position.before);
180 // is the currency symbol directly followed by the first formatted digit?
181 final char canary = formatted.charAt(symbol.length());
182 currencyGap.setValue(canary != '1');
184 else if (formatted.endsWith(symbol)) {
185 currencySymbolPosition.setValue(Currency.Position.after);
187 // is the currency symbol directly preceded bu the last formatted digit?
188 final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
189 currencyGap.setValue(canary != '6');
192 currencySymbolPosition.setValue(Currency.Position.none);
194 NumberFormat newNumberFormatter = NumberFormat.getNumberInstance();
195 newNumberFormatter.setParseIntegerOnly(false);
196 newNumberFormatter.setGroupingUsed(true);
197 newNumberFormatter.setGroupingUsed(true);
198 newNumberFormatter.setMinimumIntegerDigits(1);
199 newNumberFormatter.setMinimumFractionDigits(2);
201 numberFormatter = newNumberFormatter;
203 public static String formatCurrency(float number) {
204 NumberFormat formatter = NumberFormat.getCurrencyInstance(locale.getValue());
205 return formatter.format(number);
207 public static String formatNumber(float number) {
208 return numberFormatter.format(number);
210 public static void observeProfile(LifecycleOwner lifecycleOwner,
211 Observer<MobileLedgerProfile> observer) {
212 profile.observe(lifecycleOwner, observer);
214 public synchronized static MobileLedgerProfile initProfile() {
215 MobileLedgerProfile currentProfile = profile.getValue();
216 if (currentProfile != null)
217 return currentProfile;
219 long profileId = MLDB.getLongOption(MLDB.OPT_PROFILE_ID, 0);
220 MobileLedgerProfile startupProfile = getProfile(profileId);
221 if (startupProfile != null)
222 setCurrentProfile(startupProfile);
223 Logger.debug("profile", "initProfile() returning " + startupProfile);
224 return startupProfile;
227 public static void removeProfileObservers(LifecycleOwner owner) {
228 profile.removeObservers(owner);
230 public static float parseNumber(String str) throws ParseException {
231 ParsePosition pos = new ParsePosition(0);
232 Number parsed = numberFormatter.parse(str);
233 if (parsed == null || pos.getErrorIndex() > -1)
234 throw new ParseException("Error parsing '" + str + "'", pos.getErrorIndex());
236 return parsed.floatValue();