]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
24e3042ad193de358adec2ee48680187d4e53850
[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
36 import java.text.NumberFormat;
37 import java.text.ParseException;
38 import java.text.ParsePosition;
39 import java.util.ArrayList;
40 import java.util.Date;
41 import java.util.List;
42 import java.util.Locale;
43 import java.util.Objects;
44 import java.util.concurrent.atomic.AtomicInteger;
45
46 import static net.ktnx.mobileledger.utils.Logger.debug;
47
48 public final class Data {
49     public static final MutableLiveData<Boolean> backgroundTasksRunning =
50             new MutableLiveData<>(false);
51     public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
52             new MutableLiveData<>();
53     public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
54             new MutableLiveData<>(null);
55     public static final MutableLiveData<Currency.Position> currencySymbolPosition =
56             new MutableLiveData<>();
57     public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
58     public static final MutableLiveData<Locale> locale = new MutableLiveData<>();
59     public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
60     public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>(null);
61     public static final MutableLiveData<Integer> lastUpdateTransactionCount =
62             new MutableLiveData<>(0);
63     public static final MutableLiveData<Integer> lastUpdateAccountCount = new MutableLiveData<>(0);
64     public static final MutableLiveData<String> lastTransactionsUpdateText =
65             new MutableLiveData<>();
66     public static final MutableLiveData<String> lastAccountsUpdateText = new MutableLiveData<>();
67     private static final MutableLiveData<MobileLedgerProfile> profile =
68             new InertMutableLiveData<>();
69     private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
70     private static final Locker profilesLocker = new Locker();
71     private static NumberFormat numberFormatter;
72
73     static {
74         locale.setValue(Locale.getDefault());
75     }
76
77     @NonNull
78     public static MobileLedgerProfile getProfile() {
79         return Objects.requireNonNull(profile.getValue());
80     }
81     public static void backgroundTaskStarted() {
82         int cnt = backgroundTaskCount.incrementAndGet();
83         debug("data",
84                 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
85                         cnt));
86         backgroundTasksRunning.postValue(cnt > 0);
87     }
88     public static void backgroundTaskFinished() {
89         int cnt = backgroundTaskCount.decrementAndGet();
90         debug("data",
91                 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
92                         cnt));
93         backgroundTasksRunning.postValue(cnt > 0);
94     }
95     public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
96         MLDB.setLongOption(MLDB.OPT_PROFILE_ID, newProfile.getId());
97         profile.setValue(newProfile);
98     }
99     public static void postCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
100         MLDB.setLongOption(MLDB.OPT_PROFILE_ID, newProfile.getId());
101         profile.postValue(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(long profileId) {
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.getId() == profileId)
126                     return i;
127             }
128
129             return -1;
130         }
131     }
132     public static int retrieveCurrentThemeIdFromDb() {
133         long profileId = MLDB.getLongOption(MLDB.OPT_PROFILE_ID, 0);
134         if (profileId == 0)
135             return -1;
136
137         SQLiteDatabase db = App.getDatabase();
138         try (Cursor c = db.rawQuery("SELECT theme from profiles where id=?",
139                 new String[]{String.valueOf(profileId)}))
140         {
141             if (c.moveToNext())
142                 return c.getInt(0);
143         }
144
145         return -1;
146     }
147     @Nullable
148     public static MobileLedgerProfile getProfile(long profileId) {
149         MobileLedgerProfile profile;
150         try (LockHolder readLock = profilesLocker.lockForReading()) {
151             List<MobileLedgerProfile> prList = profiles.getValue();
152             if ((prList == null) || prList.isEmpty()) {
153                 readLock.close();
154                 try (LockHolder ignored = profilesLocker.lockForWriting()) {
155                     profile = MobileLedgerProfile.loadAllFromDB(profileId);
156                 }
157             }
158             else {
159                 int i = getProfileIndex(profileId);
160                 if (i == -1)
161                     i = 0;
162                 profile = prList.get(i);
163             }
164         }
165         return profile;
166     }
167     public static void refreshCurrencyData(Locale locale) {
168         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
169         java.util.Currency currency = formatter.getCurrency();
170         String symbol = currency != null ? currency.getSymbol() : "";
171         Logger.debug("locale", String.format(
172                 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
173                 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
174         String formatted = formatter.format(1234.56f);
175         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
176
177         if (formatted.startsWith(symbol)) {
178             currencySymbolPosition.setValue(Currency.Position.before);
179
180             // is the currency symbol directly followed by the first formatted digit?
181             final char canary = formatted.charAt(symbol.length());
182             currencyGap.setValue(canary != '1');
183         }
184         else if (formatted.endsWith(symbol)) {
185             currencySymbolPosition.setValue(Currency.Position.after);
186
187             // is the currency symbol directly preceded bu the last formatted digit?
188             final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
189             currencyGap.setValue(canary != '6');
190         }
191         else
192             currencySymbolPosition.setValue(Currency.Position.none);
193
194         NumberFormat newNumberFormatter = NumberFormat.getNumberInstance();
195         newNumberFormatter.setParseIntegerOnly(false);
196         newNumberFormatter.setGroupingUsed(true);
197         newNumberFormatter.setGroupingUsed(true);
198         newNumberFormatter.setMinimumIntegerDigits(1);
199         newNumberFormatter.setMinimumFractionDigits(2);
200
201         numberFormatter = newNumberFormatter;
202     }
203     public static String formatCurrency(float number) {
204         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale.getValue());
205         return formatter.format(number);
206     }
207     public static String formatNumber(float number) {
208         return numberFormatter.format(number);
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         long profileId = MLDB.getLongOption(MLDB.OPT_PROFILE_ID, 0);
220         MobileLedgerProfile startupProfile = getProfile(profileId);
221         if (startupProfile != null)
222             setCurrentProfile(startupProfile);
223         Logger.debug("profile", "initProfile() returning " + startupProfile);
224         return startupProfile;
225     }
226
227     public static void removeProfileObservers(LifecycleOwner owner) {
228         profile.removeObservers(owner);
229     }
230     public static float parseNumber(String str) throws ParseException {
231         ParsePosition pos = new ParsePosition(0);
232         Number parsed = numberFormatter.parse(str);
233         if (parsed == null || pos.getErrorIndex() > -1)
234             throw new ParseException("Error parsing '" + str + "'", pos.getErrorIndex());
235
236         return parsed.floatValue();
237     }
238 }