]> git.ktnx.net Git - mobile-ledger-staging.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
convert the last update global header to a list header
[mobile-ledger-staging.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> lastUpdateLiveData = new MutableLiveData<>(null);
60     public static final ObservableValue<Long> lastUpdate = new ObservableValue<>();
61     private static final MutableLiveData<MobileLedgerProfile> profile =
62             new InertMutableLiveData<>();
63     private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
64     private static final Locker profilesLocker = new Locker();
65
66     static {
67         locale.setValue(Locale.getDefault());
68     }
69
70     @NonNull
71     public static MobileLedgerProfile getProfile() {
72         return Objects.requireNonNull(profile.getValue());
73     }
74     public static void backgroundTaskStarted() {
75         int cnt = backgroundTaskCount.incrementAndGet();
76         debug("data",
77                 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
78                         cnt));
79         backgroundTasksRunning.postValue(cnt > 0);
80     }
81     public static void backgroundTaskFinished() {
82         int cnt = backgroundTaskCount.decrementAndGet();
83         debug("data",
84                 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
85                         cnt));
86         backgroundTasksRunning.postValue(cnt > 0);
87     }
88     public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
89         MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
90         profile.setValue(newProfile);
91     }
92     public static int getProfileIndex(MobileLedgerProfile profile) {
93         try (LockHolder ignored = profilesLocker.lockForReading()) {
94             List<MobileLedgerProfile> prList = profiles.getValue();
95             if (prList == null)
96                 throw new AssertionError();
97             for (int i = 0; i < prList.size(); i++) {
98                 MobileLedgerProfile p = prList.get(i);
99                 if (p.equals(profile))
100                     return i;
101             }
102
103             return -1;
104         }
105     }
106     @SuppressWarnings("WeakerAccess")
107     public static int getProfileIndex(String profileUUID) {
108         try (LockHolder ignored = profilesLocker.lockForReading()) {
109             List<MobileLedgerProfile> prList = profiles.getValue();
110             if (prList == null)
111                 throw new AssertionError();
112             for (int i = 0; i < prList.size(); i++) {
113                 MobileLedgerProfile p = prList.get(i);
114                 if (p.getUuid()
115                      .equals(profileUUID))
116                     return i;
117             }
118
119             return -1;
120         }
121     }
122     public static int retrieveCurrentThemeIdFromDb() {
123         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
124         if (profileUUID == null)
125             return -1;
126
127         SQLiteDatabase db = App.getDatabase();
128         try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
129                 new String[]{profileUUID}))
130         {
131             if (c.moveToNext())
132                 return c.getInt(0);
133         }
134
135         return -1;
136     }
137     @Nullable
138     public static MobileLedgerProfile getProfile(String profileUUID) {
139         MobileLedgerProfile profile;
140         try (LockHolder readLock = profilesLocker.lockForReading()) {
141             List<MobileLedgerProfile> prList = profiles.getValue();
142             if ((prList == null) || prList.isEmpty()) {
143                 readLock.close();
144                 try (LockHolder ignored = profilesLocker.lockForWriting()) {
145                     profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
146                 }
147             }
148             else {
149                 int i = getProfileIndex(profileUUID);
150                 if (i == -1)
151                     i = 0;
152                 profile = prList.get(i);
153             }
154         }
155         return profile;
156     }
157     public static void refreshCurrencyData(Locale locale) {
158         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
159         java.util.Currency currency = formatter.getCurrency();
160         String symbol = currency != null ? currency.getSymbol() : "";
161         Logger.debug("locale", String.format(
162                 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
163                 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
164         String formatted = formatter.format(1234.56f);
165         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
166
167         if (formatted.startsWith(symbol)) {
168             currencySymbolPosition.setValue(Currency.Position.before);
169
170             // is the currency symbol directly followed by the first formatted digit?
171             final char canary = formatted.charAt(symbol.length());
172             currencyGap.setValue(canary != '1');
173         }
174         else if (formatted.endsWith(symbol)) {
175             currencySymbolPosition.setValue(Currency.Position.after);
176
177             // is the currency symbol directly preceded bu the last formatted digit?
178             final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
179             currencyGap.setValue(canary != '6');
180         }
181         else
182             currencySymbolPosition.setValue(Currency.Position.none);
183     }
184
185     public static void observeProfile(LifecycleOwner lifecycleOwner,
186                                       Observer<MobileLedgerProfile> observer) {
187         profile.observe(lifecycleOwner, observer);
188     }
189     public synchronized static MobileLedgerProfile initProfile() {
190         MobileLedgerProfile currentProfile = profile.getValue();
191         if (currentProfile != null)
192             return currentProfile;
193
194         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
195         MobileLedgerProfile startupProfile = getProfile(profileUUID);
196         if (startupProfile != null)
197             setCurrentProfile(startupProfile);
198         return startupProfile;
199     }
200
201     public static void removeProfileObservers(LifecycleOwner owner) {
202         profile.removeObservers(owner);
203     }
204 }