]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
c0f4cebaf81c7491185fd6cc7fbd2657727904e7
[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.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
98         profile.setValue(newProfile);
99     }
100     public static void postCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
101         MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
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(String profileUUID) {
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.getUuid()
127                      .equals(profileUUID))
128                     return i;
129             }
130
131             return -1;
132         }
133     }
134     public static int retrieveCurrentThemeIdFromDb() {
135         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
136         if (profileUUID == null)
137             return -1;
138
139         SQLiteDatabase db = App.getDatabase();
140         try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
141                 new String[]{profileUUID}))
142         {
143             if (c.moveToNext())
144                 return c.getInt(0);
145         }
146
147         return -1;
148     }
149     @Nullable
150     public static MobileLedgerProfile getProfile(String profileUUID) {
151         MobileLedgerProfile profile;
152         try (LockHolder readLock = profilesLocker.lockForReading()) {
153             List<MobileLedgerProfile> prList = profiles.getValue();
154             if ((prList == null) || prList.isEmpty()) {
155                 readLock.close();
156                 try (LockHolder ignored = profilesLocker.lockForWriting()) {
157                     profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
158                 }
159             }
160             else {
161                 int i = getProfileIndex(profileUUID);
162                 if (i == -1)
163                     i = 0;
164                 profile = prList.get(i);
165             }
166         }
167         return profile;
168     }
169     public static void refreshCurrencyData(Locale locale) {
170         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
171         java.util.Currency currency = formatter.getCurrency();
172         String symbol = currency != null ? currency.getSymbol() : "";
173         Logger.debug("locale", String.format(
174                 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
175                 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
176         String formatted = formatter.format(1234.56f);
177         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
178
179         if (formatted.startsWith(symbol)) {
180             currencySymbolPosition.setValue(Currency.Position.before);
181
182             // is the currency symbol directly followed by the first formatted digit?
183             final char canary = formatted.charAt(symbol.length());
184             currencyGap.setValue(canary != '1');
185         }
186         else if (formatted.endsWith(symbol)) {
187             currencySymbolPosition.setValue(Currency.Position.after);
188
189             // is the currency symbol directly preceded bu the last formatted digit?
190             final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
191             currencyGap.setValue(canary != '6');
192         }
193         else
194             currencySymbolPosition.setValue(Currency.Position.none);
195
196         NumberFormat newNumberFormatter = NumberFormat.getNumberInstance();
197         newNumberFormatter.setParseIntegerOnly(false);
198         newNumberFormatter.setGroupingUsed(true);
199         newNumberFormatter.setGroupingUsed(true);
200         newNumberFormatter.setMinimumIntegerDigits(1);
201         newNumberFormatter.setMinimumFractionDigits(2);
202
203         numberFormatter = newNumberFormatter;
204     }
205     public static String formatCurrency(float number) {
206         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale.getValue());
207         return formatter.format(number);
208     }
209     public static String formatNumber(float number) {
210         return numberFormatter.format(number);
211     }
212     public static void observeProfile(LifecycleOwner lifecycleOwner,
213                                       Observer<MobileLedgerProfile> observer) {
214         profile.observe(lifecycleOwner, observer);
215     }
216     public synchronized static MobileLedgerProfile initProfile() {
217         MobileLedgerProfile currentProfile = profile.getValue();
218         if (currentProfile != null)
219             return currentProfile;
220
221         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
222         MobileLedgerProfile startupProfile = getProfile(profileUUID);
223         if (startupProfile != null)
224             setCurrentProfile(startupProfile);
225         Logger.debug("profile", "initProfile() returning " + startupProfile);
226         return startupProfile;
227     }
228
229     public static void removeProfileObservers(LifecycleOwner owner) {
230         profile.removeObservers(owner);
231     }
232     public static float parseNumber(String str) throws ParseException {
233         ParsePosition pos = new ParsePosition(0);
234         Number parsed = numberFormatter.parse(str);
235         if (parsed == null || pos.getErrorIndex() > -1)
236             throw new ParseException("Error parsing '" + str + "'", pos.getErrorIndex());
237
238         return parsed.floatValue();
239     }
240 }