]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
rework background progress to use MutableLiveData and observers
[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.annotation.NonNull;
25 import androidx.annotation.Nullable;
26 import androidx.lifecycle.LifecycleOwner;
27 import androidx.lifecycle.MutableLiveData;
28 import androidx.lifecycle.Observer;
29
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;
39
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;
48
49 import static net.ktnx.mobileledger.utils.Logger.debug;
50
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<>(Locale.getDefault());
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;
77     @NonNull
78     public static MobileLedgerProfile getProfile() {
79         return Objects.requireNonNull(profile.getValue());
80     }
81     public static void backgroundTaskStarted() {
82         int cnt = backgroundTaskCount.incrementAndGet();
83         debug("data",
84                 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
85                         cnt));
86         backgroundTasksRunning.postValue(cnt > 0);
87     }
88     public static void backgroundTaskFinished() {
89         int cnt = backgroundTaskCount.decrementAndGet();
90         debug("data",
91                 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
92                         cnt));
93         backgroundTasksRunning.postValue(cnt > 0);
94     }
95     public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
96         MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
97         stopTransactionsRetrieval();
98         profile.setValue(newProfile);
99     }
100     public static int getProfileIndex(MobileLedgerProfile profile) {
101         try (LockHolder ignored = profilesLocker.lockForReading()) {
102             List<MobileLedgerProfile> prList = profiles.getValue();
103             if (prList == null)
104                 throw new AssertionError();
105             for (int i = 0; i < prList.size(); i++) {
106                 MobileLedgerProfile p = prList.get(i);
107                 if (p.equals(profile))
108                     return i;
109             }
110
111             return -1;
112         }
113     }
114     @SuppressWarnings("WeakerAccess")
115     public static int getProfileIndex(String profileUUID) {
116         try (LockHolder ignored = profilesLocker.lockForReading()) {
117             List<MobileLedgerProfile> prList = profiles.getValue();
118             if (prList == null)
119                 throw new AssertionError();
120             for (int i = 0; i < prList.size(); i++) {
121                 MobileLedgerProfile p = prList.get(i);
122                 if (p.getUuid()
123                      .equals(profileUUID))
124                     return i;
125             }
126
127             return -1;
128         }
129     }
130     public static int retrieveCurrentThemeIdFromDb() {
131         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
132         if (profileUUID == null)
133             return -1;
134
135         SQLiteDatabase db = App.getDatabase();
136         try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
137                 new String[]{profileUUID}))
138         {
139             if (c.moveToNext())
140                 return c.getInt(0);
141         }
142
143         return -1;
144     }
145     @Nullable
146     public static MobileLedgerProfile getProfile(String profileUUID) {
147         MobileLedgerProfile profile;
148         try (LockHolder readLock = profilesLocker.lockForReading()) {
149             List<MobileLedgerProfile> prList = profiles.getValue();
150             if ((prList == null) || prList.isEmpty()) {
151                 readLock.close();
152                 try (LockHolder ignored = profilesLocker.lockForWriting()) {
153                     profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
154                 }
155             }
156             else {
157                 int i = getProfileIndex(profileUUID);
158                 if (i == -1)
159                     i = 0;
160                 profile = prList.get(i);
161             }
162         }
163         return profile;
164     }
165     public synchronized static void scheduleTransactionListRetrieval(MainActivity activity) {
166         if (retrieveTransactionsTask != null) {
167             Logger.debug("db", "Ignoring request for transaction retrieval - already active");
168             return;
169         }
170         MobileLedgerProfile pr = profile.getValue();
171         if (pr == null) {
172             Logger.debug("ui", "Ignoring refresh -- no current profile");
173             return;
174         }
175
176         retrieveTransactionsTask =
177                 new RetrieveTransactionsTask(new WeakReference<>(activity), profile.getValue());
178         Logger.debug("db", "Created a background transaction retrieval task");
179
180         retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
181     }
182     public static synchronized void stopTransactionsRetrieval() {
183         if (retrieveTransactionsTask != null)
184             retrieveTransactionsTask.cancel(false);
185     }
186     public static void transactionRetrievalDone() {
187         retrieveTransactionsTask = null;
188     }
189     public static void refreshCurrencyData(Locale locale) {
190         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
191         java.util.Currency currency = formatter.getCurrency();
192         String symbol = currency.getSymbol();
193         Logger.debug("locale", String.format(
194                 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
195                 locale.toString(), currency.toString(), symbol));
196         String formatted = formatter.format(1234.56f);
197         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
198
199         if (formatted.startsWith(symbol)) {
200             currencySymbolPosition.setValue(Currency.Position.before);
201
202             // is the currency symbol directly followed by the first formatted digit?
203             final char canary = formatted.charAt(symbol.length());
204             currencyGap.setValue(canary != '1');
205         }
206         else if (formatted.endsWith(symbol)) {
207             currencySymbolPosition.setValue(Currency.Position.after);
208
209             // is the currency symbol directly preceded bu the last formatted digit?
210             final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
211             currencyGap.setValue(canary != '6');
212         }
213         else
214             currencySymbolPosition.setValue(Currency.Position.none);
215     }
216
217     public static void observeProfile(LifecycleOwner lifecycleOwner,
218                                       Observer<MobileLedgerProfile> observer) {
219         profile.observe(lifecycleOwner, observer);
220     }
221     public synchronized static MobileLedgerProfile initProfile() {
222         MobileLedgerProfile currentProfile = profile.getValue();
223         if (currentProfile != null)
224             return currentProfile;
225
226         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
227         MobileLedgerProfile startupProfile = getProfile(profileUUID);
228         if (startupProfile != null)
229             setCurrentProfile(startupProfile);
230         return startupProfile;
231     }
232
233     public static void removeProfileObservers(LifecycleOwner owner) {
234         profile.removeObservers(owner);
235     }
236 }