]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
asynchronous profile initialisation
[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 androidx.annotation.NonNull;
21 import androidx.annotation.Nullable;
22 import androidx.lifecycle.LifecycleOwner;
23 import androidx.lifecycle.MutableLiveData;
24 import androidx.lifecycle.Observer;
25
26 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
27 import net.ktnx.mobileledger.utils.LockHolder;
28 import net.ktnx.mobileledger.utils.Locker;
29 import net.ktnx.mobileledger.utils.Logger;
30
31 import java.text.NumberFormat;
32 import java.text.ParseException;
33 import java.text.ParsePosition;
34 import java.util.ArrayList;
35 import java.util.Date;
36 import java.util.List;
37 import java.util.Locale;
38 import java.util.Objects;
39 import java.util.concurrent.atomic.AtomicInteger;
40
41 import static net.ktnx.mobileledger.utils.Logger.debug;
42
43 public final class Data {
44     public static final MutableLiveData<Boolean> backgroundTasksRunning =
45             new MutableLiveData<>(false);
46     public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
47             new MutableLiveData<>();
48     public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
49             new MutableLiveData<>(null);
50     public static final MutableLiveData<Currency.Position> currencySymbolPosition =
51             new MutableLiveData<>();
52     public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
53     public static final MutableLiveData<Locale> locale = new MutableLiveData<>();
54     public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
55     public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>(null);
56     public static final MutableLiveData<Integer> lastUpdateTransactionCount =
57             new MutableLiveData<>(0);
58     public static final MutableLiveData<Integer> lastUpdateAccountCount = new MutableLiveData<>(0);
59     public static final MutableLiveData<String> lastTransactionsUpdateText =
60             new MutableLiveData<>();
61     public static final MutableLiveData<String> lastAccountsUpdateText = new MutableLiveData<>();
62     private static final MutableLiveData<MobileLedgerProfile> profile =
63             new InertMutableLiveData<>();
64     private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
65     private static final Locker profilesLocker = new Locker();
66     private static NumberFormat numberFormatter;
67
68     static {
69         locale.setValue(Locale.getDefault());
70     }
71
72     @NonNull
73     public static MobileLedgerProfile getProfile() {
74         return Objects.requireNonNull(profile.getValue());
75     }
76     public static void backgroundTaskStarted() {
77         int cnt = backgroundTaskCount.incrementAndGet();
78         debug("data",
79                 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
80                         cnt));
81         backgroundTasksRunning.postValue(cnt > 0);
82     }
83     public static void backgroundTaskFinished() {
84         int cnt = backgroundTaskCount.decrementAndGet();
85         debug("data",
86                 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
87                         cnt));
88         backgroundTasksRunning.postValue(cnt > 0);
89     }
90     public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
91         profile.setValue(newProfile);
92     }
93     public static void postCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
94         profile.postValue(newProfile);
95     }
96     public static int getProfileIndex(MobileLedgerProfile profile) {
97         try (LockHolder ignored = profilesLocker.lockForReading()) {
98             List<MobileLedgerProfile> prList = profiles.getValue();
99             if (prList == null)
100                 throw new AssertionError();
101             for (int i = 0; i < prList.size(); i++) {
102                 MobileLedgerProfile p = prList.get(i);
103                 if (p.equals(profile))
104                     return i;
105             }
106
107             return -1;
108         }
109     }
110     @SuppressWarnings("WeakerAccess")
111     public static int getProfileIndex(long profileId) {
112         try (LockHolder ignored = profilesLocker.lockForReading()) {
113             List<MobileLedgerProfile> prList = profiles.getValue();
114             if (prList == null)
115                 throw new AssertionError();
116             for (int i = 0; i < prList.size(); i++) {
117                 MobileLedgerProfile p = prList.get(i);
118                 if (p.getId() == profileId)
119                     return i;
120             }
121
122             return -1;
123         }
124     }
125     @Nullable
126     public static MobileLedgerProfile getProfile(long profileId) {
127         MobileLedgerProfile profile;
128         try (LockHolder readLock = profilesLocker.lockForReading()) {
129             List<MobileLedgerProfile> prList = profiles.getValue();
130             if ((prList == null) || prList.isEmpty()) {
131                 readLock.close();
132                 try (LockHolder ignored = profilesLocker.lockForWriting()) {
133                     profile = MobileLedgerProfile.loadAllFromDB(profileId);
134                 }
135             }
136             else {
137                 int i = getProfileIndex(profileId);
138                 if (i == -1)
139                     i = 0;
140                 profile = prList.get(i);
141             }
142         }
143         return profile;
144     }
145     public static void refreshCurrencyData(Locale locale) {
146         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
147         java.util.Currency currency = formatter.getCurrency();
148         String symbol = currency != null ? currency.getSymbol() : "";
149         Logger.debug("locale", String.format(
150                 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
151                 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
152         String formatted = formatter.format(1234.56f);
153         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
154
155         if (formatted.startsWith(symbol)) {
156             currencySymbolPosition.setValue(Currency.Position.before);
157
158             // is the currency symbol directly followed by the first formatted digit?
159             final char canary = formatted.charAt(symbol.length());
160             currencyGap.setValue(canary != '1');
161         }
162         else if (formatted.endsWith(symbol)) {
163             currencySymbolPosition.setValue(Currency.Position.after);
164
165             // is the currency symbol directly preceded bu the last formatted digit?
166             final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
167             currencyGap.setValue(canary != '6');
168         }
169         else
170             currencySymbolPosition.setValue(Currency.Position.none);
171
172         NumberFormat newNumberFormatter = NumberFormat.getNumberInstance();
173         newNumberFormatter.setParseIntegerOnly(false);
174         newNumberFormatter.setGroupingUsed(true);
175         newNumberFormatter.setGroupingUsed(true);
176         newNumberFormatter.setMinimumIntegerDigits(1);
177         newNumberFormatter.setMinimumFractionDigits(2);
178
179         numberFormatter = newNumberFormatter;
180     }
181     public static String formatCurrency(float number) {
182         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale.getValue());
183         return formatter.format(number);
184     }
185     public static String formatNumber(float number) {
186         return numberFormatter.format(number);
187     }
188     public static void observeProfile(LifecycleOwner lifecycleOwner,
189                                       Observer<MobileLedgerProfile> observer) {
190         profile.observe(lifecycleOwner, observer);
191     }
192     public static void removeProfileObservers(LifecycleOwner owner) {
193         profile.removeObservers(owner);
194     }
195     public static float parseNumber(String str) throws ParseException {
196         ParsePosition pos = new ParsePosition(0);
197         Number parsed = numberFormatter.parse(str);
198         if (parsed == null || pos.getErrorIndex() > -1)
199             throw new ParseException("Error parsing '" + str + "'", pos.getErrorIndex());
200
201         return parsed.floatValue();
202     }
203 }