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