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