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.ui.activity.MainActivity;
33 import net.ktnx.mobileledger.utils.LockHolder;
34 import net.ktnx.mobileledger.utils.Locker;
35 import net.ktnx.mobileledger.utils.Logger;
36 import net.ktnx.mobileledger.utils.MLDB;
37 import net.ktnx.mobileledger.utils.ObservableList;
38 import net.ktnx.mobileledger.utils.SimpleDate;
40 import java.lang.ref.WeakReference;
41 import java.text.NumberFormat;
42 import java.util.ArrayList;
43 import java.util.Date;
44 import java.util.List;
45 import java.util.Locale;
46 import java.util.Objects;
47 import java.util.concurrent.atomic.AtomicInteger;
49 import static net.ktnx.mobileledger.utils.Logger.debug;
51 public final class Data {
52 public static final ObservableList<TransactionListItem> transactions =
53 new ObservableList<>(new ArrayList<>());
54 public static final MutableLiveData<SimpleDate> earliestTransactionDate =
55 new MutableLiveData<>(null);
56 public static final MutableLiveData<SimpleDate> latestTransactionDate =
57 new MutableLiveData<>(null);
58 public static final MutableLiveData<Boolean> backgroundTasksRunning =
59 new MutableLiveData<>(false);
60 public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
61 new MutableLiveData<>();
62 public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>();
63 public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
64 new MutableLiveData<>(null);
65 public static final MutableLiveData<String> accountFilter = new MutableLiveData<>();
66 public static final MutableLiveData<Currency.Position> currencySymbolPosition =
67 new MutableLiveData<>();
68 public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
69 public static final MutableLiveData<Locale> locale = new MutableLiveData<>();
70 public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
71 private static final MutableLiveData<MobileLedgerProfile> profile =
72 new InertMutableLiveData<>();
73 private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
74 private static final Locker profilesLocker = new Locker();
75 public static MutableLiveData<Integer> foundTransactionItemIndex = new MutableLiveData<>(null);
76 private static RetrieveTransactionsTask retrieveTransactionsTask;
79 locale.setValue(Locale.getDefault());
83 public static MobileLedgerProfile getProfile() {
84 return Objects.requireNonNull(profile.getValue());
86 public static void backgroundTaskStarted() {
87 int cnt = backgroundTaskCount.incrementAndGet();
89 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
91 backgroundTasksRunning.postValue(cnt > 0);
93 public static void backgroundTaskFinished() {
94 int cnt = backgroundTaskCount.decrementAndGet();
96 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
98 backgroundTasksRunning.postValue(cnt > 0);
100 public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
101 MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
102 stopTransactionsRetrieval();
103 profile.setValue(newProfile);
105 public static int getProfileIndex(MobileLedgerProfile profile) {
106 try (LockHolder ignored = profilesLocker.lockForReading()) {
107 List<MobileLedgerProfile> prList = profiles.getValue();
109 throw new AssertionError();
110 for (int i = 0; i < prList.size(); i++) {
111 MobileLedgerProfile p = prList.get(i);
112 if (p.equals(profile))
119 @SuppressWarnings("WeakerAccess")
120 public static int getProfileIndex(String profileUUID) {
121 try (LockHolder ignored = profilesLocker.lockForReading()) {
122 List<MobileLedgerProfile> prList = profiles.getValue();
124 throw new AssertionError();
125 for (int i = 0; i < prList.size(); i++) {
126 MobileLedgerProfile p = prList.get(i);
128 .equals(profileUUID))
135 public static int retrieveCurrentThemeIdFromDb() {
136 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
137 if (profileUUID == null)
140 SQLiteDatabase db = App.getDatabase();
141 try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
142 new String[]{profileUUID}))
151 public static MobileLedgerProfile getProfile(String profileUUID) {
152 MobileLedgerProfile profile;
153 try (LockHolder readLock = profilesLocker.lockForReading()) {
154 List<MobileLedgerProfile> prList = profiles.getValue();
155 if ((prList == null) || prList.isEmpty()) {
157 try (LockHolder ignored = profilesLocker.lockForWriting()) {
158 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
162 int i = getProfileIndex(profileUUID);
165 profile = prList.get(i);
170 public synchronized static void scheduleTransactionListRetrieval(MainActivity activity) {
171 if (retrieveTransactionsTask != null) {
172 Logger.debug("db", "Ignoring request for transaction retrieval - already active");
175 MobileLedgerProfile pr = profile.getValue();
177 Logger.debug("ui", "Ignoring refresh -- no current profile");
181 retrieveTransactionsTask =
182 new RetrieveTransactionsTask(new WeakReference<>(activity), profile.getValue());
183 Logger.debug("db", "Created a background transaction retrieval task");
185 retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
187 public static synchronized void stopTransactionsRetrieval() {
188 if (retrieveTransactionsTask != null)
189 retrieveTransactionsTask.cancel(false);
191 public static void transactionRetrievalDone() {
192 retrieveTransactionsTask = null;
194 public static void refreshCurrencyData(Locale locale) {
195 NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
196 java.util.Currency currency = formatter.getCurrency();
197 String symbol = currency != null ? currency.getSymbol() : "";
198 Logger.debug("locale", String.format(
199 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
200 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
201 String formatted = formatter.format(1234.56f);
202 Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
204 if (formatted.startsWith(symbol)) {
205 currencySymbolPosition.setValue(Currency.Position.before);
207 // is the currency symbol directly followed by the first formatted digit?
208 final char canary = formatted.charAt(symbol.length());
209 currencyGap.setValue(canary != '1');
211 else if (formatted.endsWith(symbol)) {
212 currencySymbolPosition.setValue(Currency.Position.after);
214 // is the currency symbol directly preceded bu the last formatted digit?
215 final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
216 currencyGap.setValue(canary != '6');
219 currencySymbolPosition.setValue(Currency.Position.none);
222 public static void observeProfile(LifecycleOwner lifecycleOwner,
223 Observer<MobileLedgerProfile> observer) {
224 profile.observe(lifecycleOwner, observer);
226 public synchronized static MobileLedgerProfile initProfile() {
227 MobileLedgerProfile currentProfile = profile.getValue();
228 if (currentProfile != null)
229 return currentProfile;
231 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
232 MobileLedgerProfile startupProfile = getProfile(profileUUID);
233 if (startupProfile != null)
234 setCurrentProfile(startupProfile);
235 return startupProfile;
238 public static void removeProfileObservers(LifecycleOwner owner) {
239 profile.removeObservers(owner);