]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
machinery for tracking currency format (e.g. locale) changes
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / Data.java
1 /*
2  * Copyright © 2019 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 import android.os.AsyncTask;
23
24 import androidx.lifecycle.MutableLiveData;
25
26 import net.ktnx.mobileledger.App;
27 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
28 import net.ktnx.mobileledger.ui.activity.MainActivity;
29 import net.ktnx.mobileledger.utils.LockHolder;
30 import net.ktnx.mobileledger.utils.Locker;
31 import net.ktnx.mobileledger.utils.Logger;
32 import net.ktnx.mobileledger.utils.MLDB;
33 import net.ktnx.mobileledger.utils.ObservableList;
34
35 import java.lang.ref.WeakReference;
36 import java.text.NumberFormat;
37 import java.util.ArrayList;
38 import java.util.Date;
39 import java.util.List;
40 import java.util.Locale;
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 ObservableList<TransactionListItem> transactions =
47             new ObservableList<>(new ArrayList<>());
48     public static ObservableList<LedgerAccount> accounts = new ObservableList<>(new ArrayList<>());
49     public static MutableLiveData<Boolean> backgroundTasksRunning = new MutableLiveData<>(false);
50     public static MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>();
51     public static MutableLiveData<MobileLedgerProfile> profile = new MutableLiveData<>();
52     public static MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
53             new MutableLiveData<>(null);
54     public static MutableLiveData<String> accountFilter = new MutableLiveData<>();
55     public static MutableLiveData<Currency.Position> currencySymbolPosition =
56             new MutableLiveData<>();
57     private static AtomicInteger backgroundTaskCount = new AtomicInteger(0);
58     private static Locker profilesLocker = new Locker();
59     private static RetrieveTransactionsTask retrieveTransactionsTask;
60     public static void backgroundTaskStarted() {
61         int cnt = backgroundTaskCount.incrementAndGet();
62         debug("data",
63                 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
64                         cnt));
65         backgroundTasksRunning.postValue(cnt > 0);
66     }
67     public static void backgroundTaskFinished() {
68         int cnt = backgroundTaskCount.decrementAndGet();
69         debug("data",
70                 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
71                         cnt));
72         backgroundTasksRunning.postValue(cnt > 0);
73     }
74     public static void setCurrentProfile(MobileLedgerProfile newProfile) {
75         MLDB.setOption(MLDB.OPT_PROFILE_UUID, (newProfile == null) ? null : newProfile.getUuid());
76         stopTransactionsRetrieval();
77         profile.postValue(newProfile);
78     }
79     public static int getProfileIndex(MobileLedgerProfile profile) {
80         try (LockHolder ignored = profilesLocker.lockForReading()) {
81             List<MobileLedgerProfile> prList = profiles.getValue();
82             if (prList == null) throw new AssertionError();
83             for (int i = 0; i < prList.size(); i++) {
84                 MobileLedgerProfile p = prList.get(i);
85                 if (p.equals(profile)) return i;
86             }
87
88             return -1;
89         }
90     }
91     @SuppressWarnings("WeakerAccess")
92     public static int getProfileIndex(String profileUUID) {
93         try (LockHolder ignored = profilesLocker.lockForReading()) {
94             List<MobileLedgerProfile> prList = profiles.getValue();
95             if (prList == null) throw new AssertionError();
96             for (int i = 0; i < prList.size(); i++) {
97                 MobileLedgerProfile p = prList.get(i);
98                 if (p.getUuid().equals(profileUUID)) return i;
99             }
100
101             return -1;
102         }
103     }
104     public static int retrieveCurrentThemeIdFromDb() {
105         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
106         if (profileUUID == null) return -1;
107
108         SQLiteDatabase db = App.getDatabase();
109         try (Cursor c = db
110                 .rawQuery("SELECT theme from profiles where uuid=?", new String[]{profileUUID}))
111         {
112             if (c.moveToNext()) return c.getInt(0);
113         }
114
115         return -1;
116     }
117     public static MobileLedgerProfile getProfile(String profileUUID) {
118         MobileLedgerProfile profile;
119         try (LockHolder readLock = profilesLocker.lockForReading()) {
120             List<MobileLedgerProfile> prList = profiles.getValue();
121             if ((prList == null) || prList.isEmpty()) {
122                 readLock.close();
123                 try (LockHolder ignored = profilesLocker.lockForWriting()) {
124                     profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
125                 }
126             }
127             else {
128                 int i = getProfileIndex(profileUUID);
129                 if (i == -1) i = 0;
130                 profile = prList.get(i);
131             }
132         }
133         return profile;
134     }
135     public synchronized static void scheduleTransactionListRetrieval(MainActivity activity) {
136         if (retrieveTransactionsTask != null) {
137             Logger.debug("db", "Ignoring request for transaction retrieval - already active");
138             return;
139         }
140         MobileLedgerProfile pr = profile.getValue();
141         if (pr == null) throw new IllegalStateException("No current profile");
142
143         retrieveTransactionsTask =
144                 new RetrieveTransactionsTask(new WeakReference<>(activity), profile.getValue());
145         Logger.debug("db", "Created a background transaction retrieval task");
146
147         retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
148     }
149     public static synchronized void stopTransactionsRetrieval() {
150         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
151     }
152     public static void transactionRetrievalDone() {
153         retrieveTransactionsTask = null;
154     }
155     public static void refreshCurrencyData(Locale locale) {
156         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
157         java.util.Currency currency = formatter.getCurrency();
158         Logger.debug("locale",
159                 String.format("Discovering currency symbol position for locale %s (currency is %s)",
160                         locale.toString(), currency.toString()));
161         String formatted = formatter.format(1234.56f);
162         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
163         String symbol = currency.getSymbol();
164         if (formatted.startsWith(symbol))
165             currencySymbolPosition.setValue(Currency.Position.before);
166         else if (formatted.endsWith(symbol))
167             currencySymbolPosition.setValue(Currency.Position.after);
168         else
169             currencySymbolPosition.setValue(Currency.Position.none);
170     }
171
172 }