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