]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
last update text also includes transaction count
[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
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.util.ArrayList;
39 import java.util.Date;
40 import java.util.List;
41 import java.util.Locale;
42 import java.util.Objects;
43 import java.util.concurrent.atomic.AtomicInteger;
44
45 import static net.ktnx.mobileledger.utils.Logger.debug;
46
47 public final class Data {
48     public static final MutableLiveData<Boolean> backgroundTasksRunning =
49             new MutableLiveData<>(false);
50     public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
51             new MutableLiveData<>();
52     public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
53             new MutableLiveData<>(null);
54     public static final MutableLiveData<Currency.Position> currencySymbolPosition =
55             new MutableLiveData<>();
56     public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
57     public static final MutableLiveData<Locale> locale = new MutableLiveData<>();
58     public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
59     public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>(null);
60     public static final MutableLiveData<Integer> lastUpdateTransactionCount =
61             new MutableLiveData<>(0);
62     public static final ObservableValue<String> lastUpdateText = new ObservableValue<>();
63     private static final MutableLiveData<MobileLedgerProfile> profile =
64             new InertMutableLiveData<>();
65     private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
66     private static final Locker profilesLocker = new Locker();
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         MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
92         profile.setValue(newProfile);
93     }
94     public static int getProfileIndex(MobileLedgerProfile profile) {
95         try (LockHolder ignored = profilesLocker.lockForReading()) {
96             List<MobileLedgerProfile> prList = profiles.getValue();
97             if (prList == null)
98                 throw new AssertionError();
99             for (int i = 0; i < prList.size(); i++) {
100                 MobileLedgerProfile p = prList.get(i);
101                 if (p.equals(profile))
102                     return i;
103             }
104
105             return -1;
106         }
107     }
108     @SuppressWarnings("WeakerAccess")
109     public static int getProfileIndex(String profileUUID) {
110         try (LockHolder ignored = profilesLocker.lockForReading()) {
111             List<MobileLedgerProfile> prList = profiles.getValue();
112             if (prList == null)
113                 throw new AssertionError();
114             for (int i = 0; i < prList.size(); i++) {
115                 MobileLedgerProfile p = prList.get(i);
116                 if (p.getUuid()
117                      .equals(profileUUID))
118                     return i;
119             }
120
121             return -1;
122         }
123     }
124     public static int retrieveCurrentThemeIdFromDb() {
125         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
126         if (profileUUID == null)
127             return -1;
128
129         SQLiteDatabase db = App.getDatabase();
130         try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
131                 new String[]{profileUUID}))
132         {
133             if (c.moveToNext())
134                 return c.getInt(0);
135         }
136
137         return -1;
138     }
139     @Nullable
140     public static MobileLedgerProfile getProfile(String profileUUID) {
141         MobileLedgerProfile profile;
142         try (LockHolder readLock = profilesLocker.lockForReading()) {
143             List<MobileLedgerProfile> prList = profiles.getValue();
144             if ((prList == null) || prList.isEmpty()) {
145                 readLock.close();
146                 try (LockHolder ignored = profilesLocker.lockForWriting()) {
147                     profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
148                 }
149             }
150             else {
151                 int i = getProfileIndex(profileUUID);
152                 if (i == -1)
153                     i = 0;
154                 profile = prList.get(i);
155             }
156         }
157         return profile;
158     }
159     public static void refreshCurrencyData(Locale locale) {
160         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
161         java.util.Currency currency = formatter.getCurrency();
162         String symbol = currency != null ? currency.getSymbol() : "";
163         Logger.debug("locale", String.format(
164                 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
165                 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
166         String formatted = formatter.format(1234.56f);
167         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
168
169         if (formatted.startsWith(symbol)) {
170             currencySymbolPosition.setValue(Currency.Position.before);
171
172             // is the currency symbol directly followed by the first formatted digit?
173             final char canary = formatted.charAt(symbol.length());
174             currencyGap.setValue(canary != '1');
175         }
176         else if (formatted.endsWith(symbol)) {
177             currencySymbolPosition.setValue(Currency.Position.after);
178
179             // is the currency symbol directly preceded bu the last formatted digit?
180             final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
181             currencyGap.setValue(canary != '6');
182         }
183         else
184             currencySymbolPosition.setValue(Currency.Position.none);
185     }
186
187     public static void observeProfile(LifecycleOwner lifecycleOwner,
188                                       Observer<MobileLedgerProfile> observer) {
189         profile.observe(lifecycleOwner, observer);
190     }
191     public synchronized static MobileLedgerProfile initProfile() {
192         MobileLedgerProfile currentProfile = profile.getValue();
193         if (currentProfile != null)
194             return currentProfile;
195
196         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
197         MobileLedgerProfile startupProfile = getProfile(profileUUID);
198         if (startupProfile != null)
199             setCurrentProfile(startupProfile);
200         return startupProfile;
201     }
202
203     public static void removeProfileObservers(LifecycleOwner owner) {
204         profile.removeObservers(owner);
205     }
206 }