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