]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
migrate to surrogate IDs for all database objects
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / Data.java
1 /*
2  * Copyright © 2021 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
23 import androidx.annotation.NonNull;
24 import androidx.annotation.Nullable;
25 import androidx.lifecycle.LifecycleOwner;
26 import androidx.lifecycle.MutableLiveData;
27 import androidx.lifecycle.Observer;
28
29 import net.ktnx.mobileledger.App;
30 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
31 import net.ktnx.mobileledger.utils.LockHolder;
32 import net.ktnx.mobileledger.utils.Locker;
33 import net.ktnx.mobileledger.utils.Logger;
34 import net.ktnx.mobileledger.utils.MLDB;
35 import net.ktnx.mobileledger.utils.ObservableValue;
36
37 import java.text.NumberFormat;
38 import java.text.ParseException;
39 import java.text.ParsePosition;
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 MutableLiveData<Boolean> backgroundTasksRunning =
51             new MutableLiveData<>(false);
52     public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
53             new MutableLiveData<>();
54     public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
55             new MutableLiveData<>(null);
56     public static final MutableLiveData<Currency.Position> currencySymbolPosition =
57             new MutableLiveData<>();
58     public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
59     public static final MutableLiveData<Locale> locale = new MutableLiveData<>();
60     public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
61     public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>(null);
62     public static final MutableLiveData<Integer> lastUpdateTransactionCount =
63             new MutableLiveData<>(0);
64     public static final MutableLiveData<Integer> lastUpdateAccountCount = new MutableLiveData<>(0);
65     public static final ObservableValue<String> lastTransactionsUpdateText =
66             new ObservableValue<>();
67     public static final ObservableValue<String> lastAccountsUpdateText = new ObservableValue<>();
68     private static final MutableLiveData<MobileLedgerProfile> profile =
69             new InertMutableLiveData<>();
70     private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
71     private static final Locker profilesLocker = new Locker();
72     private static NumberFormat numberFormatter;
73
74     static {
75         locale.setValue(Locale.getDefault());
76     }
77
78     @NonNull
79     public static MobileLedgerProfile getProfile() {
80         return Objects.requireNonNull(profile.getValue());
81     }
82     public static void backgroundTaskStarted() {
83         int cnt = backgroundTaskCount.incrementAndGet();
84         debug("data",
85                 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
86                         cnt));
87         backgroundTasksRunning.postValue(cnt > 0);
88     }
89     public static void backgroundTaskFinished() {
90         int cnt = backgroundTaskCount.decrementAndGet();
91         debug("data",
92                 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
93                         cnt));
94         backgroundTasksRunning.postValue(cnt > 0);
95     }
96     public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
97         MLDB.setLongOption(MLDB.OPT_PROFILE_ID, newProfile.getId());
98         profile.setValue(newProfile);
99     }
100     public static void postCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
101         MLDB.setLongOption(MLDB.OPT_PROFILE_ID, newProfile.getId());
102         profile.postValue(newProfile);
103     }
104     public static int getProfileIndex(MobileLedgerProfile profile) {
105         try (LockHolder ignored = profilesLocker.lockForReading()) {
106             List<MobileLedgerProfile> prList = profiles.getValue();
107             if (prList == null)
108                 throw new AssertionError();
109             for (int i = 0; i < prList.size(); i++) {
110                 MobileLedgerProfile p = prList.get(i);
111                 if (p.equals(profile))
112                     return i;
113             }
114
115             return -1;
116         }
117     }
118     @SuppressWarnings("WeakerAccess")
119     public static int getProfileIndex(long profileId) {
120         try (LockHolder ignored = profilesLocker.lockForReading()) {
121             List<MobileLedgerProfile> prList = profiles.getValue();
122             if (prList == null)
123                 throw new AssertionError();
124             for (int i = 0; i < prList.size(); i++) {
125                 MobileLedgerProfile p = prList.get(i);
126                 if (p.getId() == profileId)
127                     return i;
128             }
129
130             return -1;
131         }
132     }
133     public static int retrieveCurrentThemeIdFromDb() {
134         long profileId = MLDB.getLongOption(MLDB.OPT_PROFILE_ID, 0);
135         if (profileId == 0)
136             return -1;
137
138         SQLiteDatabase db = App.getDatabase();
139         try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
140                 new String[]{String.valueOf(profileId)}))
141         {
142             if (c.moveToNext())
143                 return c.getInt(0);
144         }
145
146         return -1;
147     }
148     @Nullable
149     public static MobileLedgerProfile getProfile(long profileId) {
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(profileId);
157                 }
158             }
159             else {
160                 int i = getProfileIndex(profileId);
161                 if (i == -1)
162                     i = 0;
163                 profile = prList.get(i);
164             }
165         }
166         return profile;
167     }
168     public static void refreshCurrencyData(Locale locale) {
169         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
170         java.util.Currency currency = formatter.getCurrency();
171         String symbol = currency != null ? currency.getSymbol() : "";
172         Logger.debug("locale", String.format(
173                 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
174                 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
175         String formatted = formatter.format(1234.56f);
176         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
177
178         if (formatted.startsWith(symbol)) {
179             currencySymbolPosition.setValue(Currency.Position.before);
180
181             // is the currency symbol directly followed by the first formatted digit?
182             final char canary = formatted.charAt(symbol.length());
183             currencyGap.setValue(canary != '1');
184         }
185         else if (formatted.endsWith(symbol)) {
186             currencySymbolPosition.setValue(Currency.Position.after);
187
188             // is the currency symbol directly preceded bu the last formatted digit?
189             final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
190             currencyGap.setValue(canary != '6');
191         }
192         else
193             currencySymbolPosition.setValue(Currency.Position.none);
194
195         NumberFormat newNumberFormatter = NumberFormat.getNumberInstance();
196         newNumberFormatter.setParseIntegerOnly(false);
197         newNumberFormatter.setGroupingUsed(true);
198         newNumberFormatter.setGroupingUsed(true);
199         newNumberFormatter.setMinimumIntegerDigits(1);
200         newNumberFormatter.setMinimumFractionDigits(2);
201
202         numberFormatter = newNumberFormatter;
203     }
204     public static String formatCurrency(float number) {
205         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale.getValue());
206         return formatter.format(number);
207     }
208     public static String formatNumber(float number) {
209         return numberFormatter.format(number);
210     }
211     public static void observeProfile(LifecycleOwner lifecycleOwner,
212                                       Observer<MobileLedgerProfile> observer) {
213         profile.observe(lifecycleOwner, observer);
214     }
215     public synchronized static MobileLedgerProfile initProfile() {
216         MobileLedgerProfile currentProfile = profile.getValue();
217         if (currentProfile != null)
218             return currentProfile;
219
220         long profileId = MLDB.getLongOption(MLDB.OPT_PROFILE_ID, 0);
221         MobileLedgerProfile startupProfile = getProfile(profileId);
222         if (startupProfile != null)
223             setCurrentProfile(startupProfile);
224         Logger.debug("profile", "initProfile() returning " + startupProfile);
225         return startupProfile;
226     }
227
228     public static void removeProfileObservers(LifecycleOwner owner) {
229         profile.removeObservers(owner);
230     }
231     public static float parseNumber(String str) throws ParseException {
232         ParsePosition pos = new ParsePosition(0);
233         Number parsed = numberFormatter.parse(str);
234         if (parsed == null || pos.getErrorIndex() > -1)
235             throw new ParseException("Error parsing '" + str + "'", pos.getErrorIndex());
236
237         return parsed.floatValue();
238     }
239 }