]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/MainModel.java
debug++
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / MainModel.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.ui;
19
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.os.AsyncTask;
23 import android.os.Build;
24 import android.text.TextUtils;
25
26 import androidx.annotation.Nullable;
27 import androidx.lifecycle.LiveData;
28 import androidx.lifecycle.MutableLiveData;
29 import androidx.lifecycle.ViewModel;
30
31 import net.ktnx.mobileledger.App;
32 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
33 import net.ktnx.mobileledger.async.TransactionAccumulator;
34 import net.ktnx.mobileledger.async.UpdateTransactionsTask;
35 import net.ktnx.mobileledger.model.AccountListItem;
36 import net.ktnx.mobileledger.model.Data;
37 import net.ktnx.mobileledger.model.LedgerAccount;
38 import net.ktnx.mobileledger.model.LedgerTransaction;
39 import net.ktnx.mobileledger.model.MobileLedgerProfile;
40 import net.ktnx.mobileledger.model.TransactionListItem;
41 import net.ktnx.mobileledger.utils.LockHolder;
42 import net.ktnx.mobileledger.utils.Locker;
43 import net.ktnx.mobileledger.utils.Logger;
44 import net.ktnx.mobileledger.utils.MLDB;
45 import net.ktnx.mobileledger.utils.SimpleDate;
46
47 import java.util.ArrayList;
48 import java.util.Date;
49 import java.util.HashMap;
50 import java.util.Iterator;
51 import java.util.List;
52 import java.util.Locale;
53 import java.util.Map;
54
55 import static net.ktnx.mobileledger.utils.Logger.debug;
56
57 public class MainModel extends ViewModel {
58     public final MutableLiveData<Integer> foundTransactionItemIndex = new MutableLiveData<>(null);
59     private final MutableLiveData<Boolean> updatingFlag = new MutableLiveData<>(false);
60     private final MutableLiveData<String> accountFilter = new MutableLiveData<>();
61     private final MutableLiveData<List<TransactionListItem>> displayedTransactions =
62             new MutableLiveData<>(new ArrayList<>());
63     private final MutableLiveData<List<AccountListItem>> displayedAccounts =
64             new MutableLiveData<>();
65     private final Locker accountsLocker = new Locker();
66     private final MutableLiveData<String> updateError = new MutableLiveData<>();
67     private final Map<String, LedgerAccount> accountMap = new HashMap<>();
68     private MobileLedgerProfile profile;
69     private List<LedgerAccount> allAccounts = new ArrayList<>();
70     private SimpleDate firstTransactionDate;
71     private SimpleDate lastTransactionDate;
72     transient private RetrieveTransactionsTask retrieveTransactionsTask;
73     transient private Thread displayedAccountsUpdater;
74     transient private AccountListLoader loader = null;
75     private TransactionsDisplayedFilter displayedTransactionsUpdater;
76     public static ArrayList<LedgerAccount> mergeAccountListsFromWeb(List<LedgerAccount> oldList,
77                                                                     List<LedgerAccount> newList) {
78         LedgerAccount oldAcc, newAcc;
79         ArrayList<LedgerAccount> merged = new ArrayList<>();
80
81         Iterator<LedgerAccount> oldIterator = oldList.iterator();
82         Iterator<LedgerAccount> newIterator = newList.iterator();
83
84         while (true) {
85             if (!oldIterator.hasNext()) {
86                 // the rest of the incoming are new
87                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
88                     newIterator.forEachRemaining(merged::add);
89                 }
90                 else {
91                     while (newIterator.hasNext())
92                         merged.add(newIterator.next());
93                 }
94                 break;
95             }
96             oldAcc = oldIterator.next();
97
98             if (!newIterator.hasNext()) {
99                 // no more incoming accounts. ignore the rest of the old
100                 break;
101             }
102             newAcc = newIterator.next();
103
104             // ignore now missing old items
105             if (oldAcc.getName()
106                       .compareTo(newAcc.getName()) < 0)
107                 continue;
108
109             // add newly found items
110             if (oldAcc.getName()
111                       .compareTo(newAcc.getName()) > 0)
112             {
113                 merged.add(newAcc);
114                 continue;
115             }
116
117             // two items with same account names; forward-merge UI-controlled fields
118             // it is important that the result list contains a new LedgerAccount instance
119             // so that the change is propagated to the UI
120             newAcc.setExpanded(oldAcc.isExpanded());
121             newAcc.setAmountsExpanded(oldAcc.amountsExpanded());
122             merged.add(newAcc);
123         }
124
125         return merged;
126     }
127     private void setLastUpdateStamp(long transactionCount) {
128         debug("db", "Updating transaction value stamp");
129         Date now = new Date();
130         profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
131         Data.lastUpdateDate.postValue(now);
132     }
133     public void scheduleTransactionListReload() {
134         UpdateTransactionsTask task = new UpdateTransactionsTask();
135         task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this);
136     }
137     public LiveData<Boolean> getUpdatingFlag() {
138         return updatingFlag;
139     }
140     public LiveData<String> getUpdateError() {
141         return updateError;
142     }
143     public void setProfile(MobileLedgerProfile profile) {
144         stopTransactionsRetrieval();
145         this.profile = profile;
146     }
147     public LiveData<List<TransactionListItem>> getDisplayedTransactions() {
148         return displayedTransactions;
149     }
150     public void setDisplayedTransactions(List<TransactionListItem> list, int transactionCount) {
151         displayedTransactions.postValue(list);
152         Data.lastUpdateTransactionCount.postValue(transactionCount);
153     }
154     public SimpleDate getFirstTransactionDate() {
155         return firstTransactionDate;
156     }
157     public void setFirstTransactionDate(SimpleDate earliestDate) {
158         this.firstTransactionDate = earliestDate;
159     }
160     public MutableLiveData<String> getAccountFilter() {
161         return accountFilter;
162     }
163     public SimpleDate getLastTransactionDate() {
164         return lastTransactionDate;
165     }
166     public void setLastTransactionDate(SimpleDate latestDate) {
167         this.lastTransactionDate = latestDate;
168     }
169     private void applyTransactionFilter(List<LedgerTransaction> list) {
170         final String accFilter = accountFilter.getValue();
171         ArrayList<TransactionListItem> newList = new ArrayList<>();
172
173         TransactionAccumulator accumulator = new TransactionAccumulator(this);
174         if (TextUtils.isEmpty(accFilter))
175             for (LedgerTransaction tr : list)
176                 newList.add(new TransactionListItem(tr));
177         else
178             for (LedgerTransaction tr : list)
179                 if (tr.hasAccountNamedLike(accFilter))
180                     newList.add(new TransactionListItem(tr));
181
182         displayedTransactions.postValue(newList);
183     }
184     public synchronized void scheduleTransactionListRetrieval() {
185         if (retrieveTransactionsTask != null) {
186             Logger.debug("db", "Ignoring request for transaction retrieval - already active");
187             return;
188         }
189         MobileLedgerProfile profile = Data.getProfile();
190
191         retrieveTransactionsTask = new RetrieveTransactionsTask(this, profile, allAccounts);
192         Logger.debug("db", "Created a background transaction retrieval task");
193
194         retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
195     }
196     public synchronized void stopTransactionsRetrieval() {
197         if (retrieveTransactionsTask != null)
198             retrieveTransactionsTask.cancel(true);
199     }
200     public void transactionRetrievalDone() {
201         retrieveTransactionsTask = null;
202     }
203     public synchronized Locker lockAccountsForWriting() {
204         accountsLocker.lockForWriting();
205         return accountsLocker;
206     }
207     public void mergeAccountListFromWeb(List<LedgerAccount> newList) {
208
209         try (LockHolder l = accountsLocker.lockForWriting()) {
210             allAccounts = mergeAccountListsFromWeb(allAccounts, newList);
211             updateAccountsMap(allAccounts);
212         }
213     }
214     public LiveData<List<AccountListItem>> getDisplayedAccounts() {
215         return displayedAccounts;
216     }
217     synchronized public void scheduleAccountListReload() {
218         Logger.debug("async-acc", "scheduleAccountListReload() enter");
219         if ((loader != null) && loader.isAlive()) {
220             Logger.debug("async-acc", "returning early - loader already active");
221             return;
222         }
223
224         loader = new AccountListLoader(profile, this);
225         loader.start();
226     }
227     public synchronized void setAndStoreAccountAndTransactionListFromWeb(
228             List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
229         profile.storeAccountAndTransactionListAsync(accounts, transactions);
230
231         setLastUpdateStamp(transactions.size());
232
233         mergeAccountListFromWeb(accounts);
234         updateDisplayedAccounts();
235
236         updateDisplayedTransactionsFromWeb(transactions);
237     }
238     synchronized public void abortAccountListReload() {
239         if (loader == null)
240             return;
241         loader.interrupt();
242         loader = null;
243     }
244     synchronized public void updateDisplayedAccounts() {
245         if (displayedAccountsUpdater != null) {
246             displayedAccountsUpdater.interrupt();
247         }
248         displayedAccountsUpdater = new AccountListDisplayedFilter(this, allAccounts);
249         displayedAccountsUpdater.start();
250     }
251     synchronized public void updateDisplayedTransactionsFromWeb(List<LedgerTransaction> list) {
252         if (displayedTransactionsUpdater != null) {
253             displayedTransactionsUpdater.interrupt();
254         }
255         displayedTransactionsUpdater = new TransactionsDisplayedFilter(this, list);
256         displayedTransactionsUpdater.start();
257     }
258     public List<LedgerAccount> getAllAccounts() {
259         return allAccounts;
260     }
261     private void updateAccountsMap(List<LedgerAccount> newAccounts) {
262         accountMap.clear();
263         for (LedgerAccount acc : newAccounts) {
264             accountMap.put(acc.getName(), acc);
265         }
266     }
267     @Nullable
268     public LedgerAccount locateAccount(String name) {
269         return accountMap.get(name);
270     }
271     public void clearUpdateError() {
272         updateError.postValue(null);
273     }
274     public void clearAccounts() { displayedAccounts.postValue(new ArrayList<>()); }
275     public void clearTransactions() {
276         displayedTransactions.setValue(new ArrayList<>());
277     }
278
279     static class AccountListLoader extends Thread {
280         private final MobileLedgerProfile profile;
281         private final MainModel model;
282         AccountListLoader(MobileLedgerProfile profile, MainModel model) {
283             this.profile = profile;
284             this.model = model;
285         }
286         @Override
287         public void run() {
288             Logger.debug("async-acc", "AccountListLoader::run() entered");
289             String profileUUID = profile.getUuid();
290             ArrayList<LedgerAccount> list = new ArrayList<>();
291             HashMap<String, LedgerAccount> map = new HashMap<>();
292
293             String sql = "SELECT a.name, a.expanded, a.amounts_expanded";
294             sql += " from accounts a WHERE a.profile = ?";
295             sql += " ORDER BY a.name";
296
297             SQLiteDatabase db = App.getDatabase();
298             Logger.debug("async-acc", "AccountListLoader::run() connected to DB");
299             try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
300                 Logger.debug("async-acc", "AccountListLoader::run() executed query");
301                 while (cursor.moveToNext()) {
302                     if (isInterrupted())
303                         return;
304
305                     final String accName = cursor.getString(0);
306 //                    debug("accounts",
307 //                            String.format("Read account '%s' from DB [%s]", accName,
308 //                            profileUUID));
309                     String parentName = LedgerAccount.extractParentName(accName);
310                     LedgerAccount parent;
311                     if (parentName != null) {
312                         parent = map.get(parentName);
313                         if (parent == null)
314                             throw new IllegalStateException(
315                                     String.format("Can't load account '%s': parent '%s' not loaded",
316                                             accName, parentName));
317                         parent.setHasSubAccounts(true);
318                     }
319                     else
320                         parent = null;
321
322                     LedgerAccount acc = new LedgerAccount(profile, accName, parent);
323                     acc.setExpanded(cursor.getInt(1) == 1);
324                     acc.setAmountsExpanded(cursor.getInt(2) == 1);
325                     acc.setHasSubAccounts(false);
326
327                     try (Cursor c2 = db.rawQuery(
328                             "SELECT value, currency FROM account_values WHERE profile = ?" + " " +
329                             "AND account = ?", new String[]{profileUUID, accName}))
330                     {
331                         while (c2.moveToNext()) {
332                             acc.addAmount(c2.getFloat(0), c2.getString(1));
333                         }
334                     }
335
336                     list.add(acc);
337                     map.put(accName, acc);
338                 }
339                 Logger.debug("async-acc", "AccountListLoader::run() query execution done");
340             }
341
342             if (isInterrupted())
343                 return;
344
345             Logger.debug("async-acc", "AccountListLoader::run() posting new list");
346             model.allAccounts = list;
347             model.updateAccountsMap(list);
348             model.updateDisplayedAccounts();
349         }
350     }
351
352     static class AccountListDisplayedFilter extends Thread {
353         private final MainModel model;
354         private final List<LedgerAccount> list;
355         AccountListDisplayedFilter(MainModel model, List<LedgerAccount> list) {
356             this.model = model;
357             this.list = list;
358         }
359         @Override
360         public void run() {
361             List<AccountListItem> newDisplayed = new ArrayList<>();
362             Logger.debug("dFilter", "waiting for synchronized block");
363             Logger.debug("dFilter", String.format(Locale.US,
364                     "entered synchronized block (about to examine %d accounts)", list.size()));
365             newDisplayed.add(new AccountListItem());    // header
366
367             int count = 0;
368             for (LedgerAccount a : list) {
369                 if (isInterrupted())
370                     return;
371
372                 if (a.isVisible()) {
373                     newDisplayed.add(new AccountListItem(a));
374                     count++;
375                 }
376             }
377             if (!isInterrupted()) {
378                 model.displayedAccounts.postValue(newDisplayed);
379                 Data.lastUpdateAccountCount.postValue(count);
380             }
381             Logger.debug("dFilter", "left synchronized block");
382         }
383     }
384
385     static class TransactionsDisplayedFilter extends Thread {
386         private final MainModel model;
387         private final List<LedgerTransaction> list;
388         TransactionsDisplayedFilter(MainModel model, List<LedgerTransaction> list) {
389             this.model = model;
390             this.list = list;
391         }
392         @Override
393         public void run() {
394             List<LedgerAccount> newDisplayed = new ArrayList<>();
395             Logger.debug("dFilter", "waiting for synchronized block");
396             Logger.debug("dFilter", String.format(Locale.US,
397                     "entered synchronized block (about to examine %d transactions)", list.size()));
398             String accNameFilter = model.getAccountFilter()
399                                         .getValue();
400
401             TransactionAccumulator acc = new TransactionAccumulator(model);
402             for (LedgerTransaction tr : list) {
403                 if (isInterrupted()) {
404                     return;
405                 }
406
407                 if (accNameFilter == null || tr.hasAccountNamedLike(accNameFilter)) {
408                     acc.put(tr, tr.getDate());
409                 }
410             }
411             if (!isInterrupted()) {
412                 acc.done();
413             }
414             Logger.debug("dFilter", "left synchronized block");
415         }
416     }
417 }