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