]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
more asynchronous account list (re-)loading
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / Data.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.model;
19
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.os.AsyncTask;
23
24 import androidx.lifecycle.MutableLiveData;
25
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;
35
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;
43
44 import static net.ktnx.mobileledger.utils.Logger.debug;
45
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<MobileLedgerProfile> profile = new InertMutableLiveData<>();
57     public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
58             new MutableLiveData<>(null);
59     public static final MutableLiveData<String> accountFilter = new MutableLiveData<>();
60     public static final MutableLiveData<Currency.Position> currencySymbolPosition =
61             new MutableLiveData<>();
62     public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
63     public static final MutableLiveData<Locale> locale = new MutableLiveData<>(Locale.getDefault());
64     private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
65     private static final Locker profilesLocker = new Locker();
66     public static MutableLiveData<Integer> foundTransactionItemIndex = new MutableLiveData<>(null);
67     private static RetrieveTransactionsTask retrieveTransactionsTask;
68     public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
69     public static void backgroundTaskStarted() {
70         int cnt = backgroundTaskCount.incrementAndGet();
71         debug("data",
72                 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
73                         cnt));
74         backgroundTasksRunning.postValue(cnt > 0);
75     }
76     public static void backgroundTaskFinished() {
77         int cnt = backgroundTaskCount.decrementAndGet();
78         debug("data",
79                 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
80                         cnt));
81         backgroundTasksRunning.postValue(cnt > 0);
82     }
83     public static void setCurrentProfile(MobileLedgerProfile newProfile) {
84         MLDB.setOption(MLDB.OPT_PROFILE_UUID, (newProfile == null) ? null : newProfile.getUuid());
85         stopTransactionsRetrieval();
86         profile.setValue(newProfile);
87     }
88     public static int getProfileIndex(MobileLedgerProfile profile) {
89         try (LockHolder ignored = profilesLocker.lockForReading()) {
90             List<MobileLedgerProfile> prList = profiles.getValue();
91             if (prList == null)
92                 throw new AssertionError();
93             for (int i = 0; i < prList.size(); i++) {
94                 MobileLedgerProfile p = prList.get(i);
95                 if (p.equals(profile))
96                     return i;
97             }
98
99             return -1;
100         }
101     }
102     @SuppressWarnings("WeakerAccess")
103     public static int getProfileIndex(String profileUUID) {
104         try (LockHolder ignored = profilesLocker.lockForReading()) {
105             List<MobileLedgerProfile> prList = profiles.getValue();
106             if (prList == null)
107                 throw new AssertionError();
108             for (int i = 0; i < prList.size(); i++) {
109                 MobileLedgerProfile p = prList.get(i);
110                 if (p.getUuid()
111                      .equals(profileUUID))
112                     return i;
113             }
114
115             return -1;
116         }
117     }
118     public static int retrieveCurrentThemeIdFromDb() {
119         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
120         if (profileUUID == null)
121             return -1;
122
123         SQLiteDatabase db = App.getDatabase();
124         try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
125                 new String[]{profileUUID}))
126         {
127             if (c.moveToNext())
128                 return c.getInt(0);
129         }
130
131         return -1;
132     }
133     public static MobileLedgerProfile getProfile(String profileUUID) {
134         MobileLedgerProfile profile;
135         try (LockHolder readLock = profilesLocker.lockForReading()) {
136             List<MobileLedgerProfile> prList = profiles.getValue();
137             if ((prList == null) || prList.isEmpty()) {
138                 readLock.close();
139                 try (LockHolder ignored = profilesLocker.lockForWriting()) {
140                     profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
141                 }
142             }
143             else {
144                 int i = getProfileIndex(profileUUID);
145                 if (i == -1)
146                     i = 0;
147                 profile = prList.get(i);
148             }
149         }
150         return profile;
151     }
152     public synchronized static void scheduleTransactionListRetrieval(MainActivity activity) {
153         if (retrieveTransactionsTask != null) {
154             Logger.debug("db", "Ignoring request for transaction retrieval - already active");
155             return;
156         }
157         MobileLedgerProfile pr = profile.getValue();
158         if (pr == null) {
159             Logger.debug("ui", "Ignoring refresh -- no current profile");
160             return;
161         }
162
163         retrieveTransactionsTask =
164                 new RetrieveTransactionsTask(new WeakReference<>(activity), profile.getValue());
165         Logger.debug("db", "Created a background transaction retrieval task");
166
167         retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
168     }
169     public static synchronized void stopTransactionsRetrieval() {
170         if (retrieveTransactionsTask != null)
171             retrieveTransactionsTask.cancel(false);
172     }
173     public static void transactionRetrievalDone() {
174         retrieveTransactionsTask = null;
175     }
176     public static void refreshCurrencyData(Locale locale) {
177         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
178         java.util.Currency currency = formatter.getCurrency();
179         String symbol = currency.getSymbol();
180         Logger.debug("locale", String.format(
181                 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
182                 locale.toString(), currency.toString(), symbol));
183         String formatted = formatter.format(1234.56f);
184         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
185
186         if (formatted.startsWith(symbol)) {
187             currencySymbolPosition.setValue(Currency.Position.before);
188
189             // is the currency symbol directly followed by the first formatted digit?
190             final char canary = formatted.charAt(symbol.length());
191             currencyGap.setValue(canary != '1');
192         }
193         else if (formatted.endsWith(symbol)) {
194             currencySymbolPosition.setValue(Currency.Position.after);
195
196             // is the currency symbol directly preceded bu the last formatted digit?
197             final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
198             currencyGap.setValue(canary != '6');
199         }
200         else
201             currencySymbolPosition.setValue(Currency.Position.none);
202     }
203
204 }