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.annotation.NonNull;
25 import androidx.annotation.Nullable;
26 import androidx.lifecycle.LifecycleOwner;
27 import androidx.lifecycle.MutableLiveData;
28 import androidx.lifecycle.Observer;
30 import net.ktnx.mobileledger.App;
31 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
32 import net.ktnx.mobileledger.utils.LockHolder;
33 import net.ktnx.mobileledger.utils.Locker;
34 import net.ktnx.mobileledger.utils.Logger;
35 import net.ktnx.mobileledger.utils.MLDB;
36 import net.ktnx.mobileledger.utils.ObservableList;
37 import net.ktnx.mobileledger.utils.SimpleDate;
39 import java.text.NumberFormat;
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 ObservableList<TransactionListItem> transactions =
51 new ObservableList<>(new ArrayList<>());
52 public static final MutableLiveData<SimpleDate> earliestTransactionDate =
53 new MutableLiveData<>(null);
54 public static final MutableLiveData<SimpleDate> latestTransactionDate =
55 new MutableLiveData<>(null);
56 public static final MutableLiveData<Boolean> backgroundTasksRunning =
57 new MutableLiveData<>(false);
58 public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
59 new MutableLiveData<>();
60 public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>();
61 public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
62 new MutableLiveData<>(null);
63 public static final MutableLiveData<String> accountFilter = new MutableLiveData<>();
64 public static final MutableLiveData<Currency.Position> currencySymbolPosition =
65 new MutableLiveData<>();
66 public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
67 public static final MutableLiveData<Locale> locale = new MutableLiveData<>();
68 public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
69 private static final MutableLiveData<MobileLedgerProfile> profile =
70 new InertMutableLiveData<>();
71 private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
72 private static final Locker profilesLocker = new Locker();
73 public static MutableLiveData<Integer> foundTransactionItemIndex = new MutableLiveData<>(null);
74 private static RetrieveTransactionsTask retrieveTransactionsTask;
77 locale.setValue(Locale.getDefault());
81 public static MobileLedgerProfile getProfile() {
82 return Objects.requireNonNull(profile.getValue());
84 public static void backgroundTaskStarted() {
85 int cnt = backgroundTaskCount.incrementAndGet();
87 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
89 backgroundTasksRunning.postValue(cnt > 0);
91 public static void backgroundTaskFinished() {
92 int cnt = backgroundTaskCount.decrementAndGet();
94 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
96 backgroundTasksRunning.postValue(cnt > 0);
98 public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
99 MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
100 stopTransactionsRetrieval();
101 profile.setValue(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(String profileUUID) {
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);
126 .equals(profileUUID))
133 public static int retrieveCurrentThemeIdFromDb() {
134 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
135 if (profileUUID == null)
138 SQLiteDatabase db = App.getDatabase();
139 try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
140 new String[]{profileUUID}))
149 public static MobileLedgerProfile getProfile(String profileUUID) {
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(profileUUID);
160 int i = getProfileIndex(profileUUID);
163 profile = prList.get(i);
168 public synchronized static void scheduleTransactionListRetrieval() {
169 if (retrieveTransactionsTask != null) {
170 Logger.debug("db", "Ignoring request for transaction retrieval - already active");
173 MobileLedgerProfile pr = profile.getValue();
175 Logger.debug("ui", "Ignoring refresh -- no current profile");
179 retrieveTransactionsTask = new RetrieveTransactionsTask(profile.getValue());
180 Logger.debug("db", "Created a background transaction retrieval task");
182 retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
184 public static synchronized void stopTransactionsRetrieval() {
185 if (retrieveTransactionsTask != null)
186 retrieveTransactionsTask.cancel(false);
188 public static void transactionRetrievalDone() {
189 retrieveTransactionsTask = null;
191 public static void refreshCurrencyData(Locale locale) {
192 NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
193 java.util.Currency currency = formatter.getCurrency();
194 String symbol = currency != null ? currency.getSymbol() : "";
195 Logger.debug("locale", String.format(
196 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
197 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
198 String formatted = formatter.format(1234.56f);
199 Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
201 if (formatted.startsWith(symbol)) {
202 currencySymbolPosition.setValue(Currency.Position.before);
204 // is the currency symbol directly followed by the first formatted digit?
205 final char canary = formatted.charAt(symbol.length());
206 currencyGap.setValue(canary != '1');
208 else if (formatted.endsWith(symbol)) {
209 currencySymbolPosition.setValue(Currency.Position.after);
211 // is the currency symbol directly preceded bu the last formatted digit?
212 final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
213 currencyGap.setValue(canary != '6');
216 currencySymbolPosition.setValue(Currency.Position.none);
219 public static void observeProfile(LifecycleOwner lifecycleOwner,
220 Observer<MobileLedgerProfile> observer) {
221 profile.observe(lifecycleOwner, observer);
223 public synchronized static MobileLedgerProfile initProfile() {
224 MobileLedgerProfile currentProfile = profile.getValue();
225 if (currentProfile != null)
226 return currentProfile;
228 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
229 MobileLedgerProfile startupProfile = getProfile(profileUUID);
230 if (startupProfile != null)
231 setCurrentProfile(startupProfile);
232 return startupProfile;
235 public static void removeProfileObservers(LifecycleOwner owner) {
236 profile.removeObservers(owner);