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