]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
move locale live-data initialization to a static initialization block
[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<>();
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
78     static {
79         locale.setValue(Locale.getDefault());
80     }
81
82     @NonNull
83     public static MobileLedgerProfile getProfile() {
84         return Objects.requireNonNull(profile.getValue());
85     }
86     public static void backgroundTaskStarted() {
87         int cnt = backgroundTaskCount.incrementAndGet();
88         debug("data",
89                 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
90                         cnt));
91         backgroundTasksRunning.postValue(cnt > 0);
92     }
93     public static void backgroundTaskFinished() {
94         int cnt = backgroundTaskCount.decrementAndGet();
95         debug("data",
96                 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
97                         cnt));
98         backgroundTasksRunning.postValue(cnt > 0);
99     }
100     public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
101         MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
102         stopTransactionsRetrieval();
103         profile.setValue(newProfile);
104     }
105     public static int getProfileIndex(MobileLedgerProfile profile) {
106         try (LockHolder ignored = profilesLocker.lockForReading()) {
107             List<MobileLedgerProfile> prList = profiles.getValue();
108             if (prList == null)
109                 throw new AssertionError();
110             for (int i = 0; i < prList.size(); i++) {
111                 MobileLedgerProfile p = prList.get(i);
112                 if (p.equals(profile))
113                     return i;
114             }
115
116             return -1;
117         }
118     }
119     @SuppressWarnings("WeakerAccess")
120     public static int getProfileIndex(String profileUUID) {
121         try (LockHolder ignored = profilesLocker.lockForReading()) {
122             List<MobileLedgerProfile> prList = profiles.getValue();
123             if (prList == null)
124                 throw new AssertionError();
125             for (int i = 0; i < prList.size(); i++) {
126                 MobileLedgerProfile p = prList.get(i);
127                 if (p.getUuid()
128                      .equals(profileUUID))
129                     return i;
130             }
131
132             return -1;
133         }
134     }
135     public static int retrieveCurrentThemeIdFromDb() {
136         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
137         if (profileUUID == null)
138             return -1;
139
140         SQLiteDatabase db = App.getDatabase();
141         try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
142                 new String[]{profileUUID}))
143         {
144             if (c.moveToNext())
145                 return c.getInt(0);
146         }
147
148         return -1;
149     }
150     @Nullable
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()) {
156                 readLock.close();
157                 try (LockHolder ignored = profilesLocker.lockForWriting()) {
158                     profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
159                 }
160             }
161             else {
162                 int i = getProfileIndex(profileUUID);
163                 if (i == -1)
164                     i = 0;
165                 profile = prList.get(i);
166             }
167         }
168         return profile;
169     }
170     public synchronized static void scheduleTransactionListRetrieval(MainActivity activity) {
171         if (retrieveTransactionsTask != null) {
172             Logger.debug("db", "Ignoring request for transaction retrieval - already active");
173             return;
174         }
175         MobileLedgerProfile pr = profile.getValue();
176         if (pr == null) {
177             Logger.debug("ui", "Ignoring refresh -- no current profile");
178             return;
179         }
180
181         retrieveTransactionsTask =
182                 new RetrieveTransactionsTask(new WeakReference<>(activity), profile.getValue());
183         Logger.debug("db", "Created a background transaction retrieval task");
184
185         retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
186     }
187     public static synchronized void stopTransactionsRetrieval() {
188         if (retrieveTransactionsTask != null)
189             retrieveTransactionsTask.cancel(false);
190     }
191     public static void transactionRetrievalDone() {
192         retrieveTransactionsTask = null;
193     }
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));
203
204         if (formatted.startsWith(symbol)) {
205             currencySymbolPosition.setValue(Currency.Position.before);
206
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');
210         }
211         else if (formatted.endsWith(symbol)) {
212             currencySymbolPosition.setValue(Currency.Position.after);
213
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');
217         }
218         else
219             currencySymbolPosition.setValue(Currency.Position.none);
220     }
221
222     public static void observeProfile(LifecycleOwner lifecycleOwner,
223                                       Observer<MobileLedgerProfile> observer) {
224         profile.observe(lifecycleOwner, observer);
225     }
226     public synchronized static MobileLedgerProfile initProfile() {
227         MobileLedgerProfile currentProfile = profile.getValue();
228         if (currentProfile != null)
229             return currentProfile;
230
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;
236     }
237
238     public static void removeProfileObservers(LifecycleOwner owner) {
239         profile.removeObservers(owner);
240     }
241 }