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