2 * Copyright © 2020 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;
22 import android.os.AsyncTask;
24 import androidx.lifecycle.MutableLiveData;
26 import net.ktnx.mobileledger.App;
27 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
28 import net.ktnx.mobileledger.ui.activity.MainActivity;
29 import net.ktnx.mobileledger.utils.LockHolder;
30 import net.ktnx.mobileledger.utils.Locker;
31 import net.ktnx.mobileledger.utils.Logger;
32 import net.ktnx.mobileledger.utils.MLDB;
33 import net.ktnx.mobileledger.utils.ObservableList;
34 import net.ktnx.mobileledger.utils.SimpleDate;
36 import java.lang.ref.WeakReference;
37 import java.text.NumberFormat;
38 import java.util.ArrayList;
39 import java.util.Date;
40 import java.util.List;
41 import java.util.Locale;
42 import java.util.concurrent.atomic.AtomicInteger;
44 import static net.ktnx.mobileledger.utils.Logger.debug;
46 public final class Data {
47 public static final ObservableList<TransactionListItem> transactions =
48 new ObservableList<>(new ArrayList<>());
49 public static final MutableLiveData<SimpleDate> earliestTransactionDate =
50 new MutableLiveData<>(null);
51 public static final MutableLiveData<SimpleDate> latestTransactionDate =
52 new MutableLiveData<>(null);
53 public static final MutableLiveData<Boolean> backgroundTasksRunning =
54 new MutableLiveData<>(false);
55 public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>();
56 public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
57 new MutableLiveData<>(null);
58 public static final MutableLiveData<String> accountFilter = new MutableLiveData<>();
59 public static final MutableLiveData<Currency.Position> currencySymbolPosition =
60 new MutableLiveData<>();
61 public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
62 public static final MutableLiveData<Locale> locale = new MutableLiveData<>(Locale.getDefault());
63 private static final MutableLiveData<MobileLedgerProfile> profile =
64 new InertMutableLiveData<>();
65 private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
66 private static final Locker profilesLocker = new Locker();
67 public static MutableLiveData<Integer> foundTransactionItemIndex = new MutableLiveData<>(null);
68 private static RetrieveTransactionsTask retrieveTransactionsTask;
70 public static MobileLedgerProfile getProfile() {
71 return Objects.requireNonNull(profile.getValue());
73 public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
74 public static void backgroundTaskStarted() {
75 int cnt = backgroundTaskCount.incrementAndGet();
77 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
79 backgroundTasksRunning.postValue(cnt > 0);
81 public static void backgroundTaskFinished() {
82 int cnt = backgroundTaskCount.decrementAndGet();
84 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
86 backgroundTasksRunning.postValue(cnt > 0);
88 public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
89 MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
90 stopTransactionsRetrieval();
91 profile.setValue(newProfile);
93 public static int getProfileIndex(MobileLedgerProfile profile) {
94 try (LockHolder ignored = profilesLocker.lockForReading()) {
95 List<MobileLedgerProfile> prList = profiles.getValue();
97 throw new AssertionError();
98 for (int i = 0; i < prList.size(); i++) {
99 MobileLedgerProfile p = prList.get(i);
100 if (p.equals(profile))
107 @SuppressWarnings("WeakerAccess")
108 public static int getProfileIndex(String profileUUID) {
109 try (LockHolder ignored = profilesLocker.lockForReading()) {
110 List<MobileLedgerProfile> prList = profiles.getValue();
112 throw new AssertionError();
113 for (int i = 0; i < prList.size(); i++) {
114 MobileLedgerProfile p = prList.get(i);
116 .equals(profileUUID))
123 public static int retrieveCurrentThemeIdFromDb() {
124 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
125 if (profileUUID == null)
128 SQLiteDatabase db = App.getDatabase();
129 try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
130 new String[]{profileUUID}))
139 public static MobileLedgerProfile getProfile(String profileUUID) {
140 MobileLedgerProfile profile;
141 try (LockHolder readLock = profilesLocker.lockForReading()) {
142 List<MobileLedgerProfile> prList = profiles.getValue();
143 if ((prList == null) || prList.isEmpty()) {
145 try (LockHolder ignored = profilesLocker.lockForWriting()) {
146 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
150 int i = getProfileIndex(profileUUID);
153 profile = prList.get(i);
158 public synchronized static void scheduleTransactionListRetrieval(MainActivity activity) {
159 if (retrieveTransactionsTask != null) {
160 Logger.debug("db", "Ignoring request for transaction retrieval - already active");
163 MobileLedgerProfile pr = profile.getValue();
165 Logger.debug("ui", "Ignoring refresh -- no current profile");
169 retrieveTransactionsTask =
170 new RetrieveTransactionsTask(new WeakReference<>(activity), profile.getValue());
171 Logger.debug("db", "Created a background transaction retrieval task");
173 retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
175 public static synchronized void stopTransactionsRetrieval() {
176 if (retrieveTransactionsTask != null)
177 retrieveTransactionsTask.cancel(false);
179 public static void transactionRetrievalDone() {
180 retrieveTransactionsTask = null;
182 public static void refreshCurrencyData(Locale locale) {
183 NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
184 java.util.Currency currency = formatter.getCurrency();
185 String symbol = currency.getSymbol();
186 Logger.debug("locale", String.format(
187 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
188 locale.toString(), currency.toString(), symbol));
189 String formatted = formatter.format(1234.56f);
190 Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
192 if (formatted.startsWith(symbol)) {
193 currencySymbolPosition.setValue(Currency.Position.before);
195 // is the currency symbol directly followed by the first formatted digit?
196 final char canary = formatted.charAt(symbol.length());
197 currencyGap.setValue(canary != '1');
199 else if (formatted.endsWith(symbol)) {
200 currencySymbolPosition.setValue(Currency.Position.after);
202 // is the currency symbol directly preceded bu the last formatted digit?
203 final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
204 currencyGap.setValue(canary != '6');
207 currencySymbolPosition.setValue(Currency.Position.none);
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 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
220 MobileLedgerProfile startupProfile = getProfile(profileUUID);
221 if (startupProfile != null)
222 setCurrentProfile(startupProfile);
223 return startupProfile;
226 public static void removeProfileObservers(LifecycleOwner owner) {
227 profile.removeObservers(owner);