]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/MainModel.java
5ca0e0be00c4cc5e05c73751a16be9eaba6e5ebc
[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 clearTransactions() {
275         displayedTransactions.setValue(new ArrayList<>());
276     }
277
278     static class AccountListLoader extends Thread {
279         private final MobileLedgerProfile profile;
280         private final MainModel model;
281         AccountListLoader(MobileLedgerProfile profile, MainModel model) {
282             this.profile = profile;
283             this.model = model;
284         }
285         @Override
286         public void run() {
287             Logger.debug("async-acc", "AccountListLoader::run() entered");
288             String profileUUID = profile.getUuid();
289             ArrayList<LedgerAccount> list = new ArrayList<>();
290             HashMap<String, LedgerAccount> map = new HashMap<>();
291
292             String sql = "SELECT a.name, a.expanded, a.amounts_expanded";
293             sql += " from accounts a WHERE a.profile = ?";
294             sql += " ORDER BY a.name";
295
296             SQLiteDatabase db = App.getDatabase();
297             Logger.debug("async-acc", "AccountListLoader::run() connected to DB");
298             try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
299                 Logger.debug("async-acc", "AccountListLoader::run() executed query");
300                 while (cursor.moveToNext()) {
301                     if (isInterrupted())
302                         return;
303
304                     final String accName = cursor.getString(0);
305 //                    debug("accounts",
306 //                            String.format("Read account '%s' from DB [%s]", accName,
307 //                            profileUUID));
308                     String parentName = LedgerAccount.extractParentName(accName);
309                     LedgerAccount parent;
310                     if (parentName != null) {
311                         parent = map.get(parentName);
312                         if (parent == null)
313                             throw new IllegalStateException(
314                                     String.format("Can't load account '%s': parent '%s' not loaded",
315                                             accName, parentName));
316                         parent.setHasSubAccounts(true);
317                     }
318                     else
319                         parent = null;
320
321                     LedgerAccount acc = new LedgerAccount(profile, accName, parent);
322                     acc.setExpanded(cursor.getInt(1) == 1);
323                     acc.setAmountsExpanded(cursor.getInt(2) == 1);
324                     acc.setHasSubAccounts(false);
325
326                     try (Cursor c2 = db.rawQuery(
327                             "SELECT value, currency FROM account_values WHERE profile = ?" + " " +
328                             "AND account = ?", new String[]{profileUUID, accName}))
329                     {
330                         while (c2.moveToNext()) {
331                             acc.addAmount(c2.getFloat(0), c2.getString(1));
332                         }
333                     }
334
335                     list.add(acc);
336                     map.put(accName, acc);
337                 }
338                 Logger.debug("async-acc", "AccountListLoader::run() query execution done");
339             }
340
341             if (isInterrupted())
342                 return;
343
344             Logger.debug("async-acc", "AccountListLoader::run() posting new list");
345             model.allAccounts = list;
346             model.updateAccountsMap(list);
347             model.updateDisplayedAccounts();
348         }
349     }
350
351     static class AccountListDisplayedFilter extends Thread {
352         private final MainModel model;
353         private final List<LedgerAccount> list;
354         AccountListDisplayedFilter(MainModel model, List<LedgerAccount> list) {
355             this.model = model;
356             this.list = list;
357         }
358         @Override
359         public void run() {
360             List<AccountListItem> newDisplayed = new ArrayList<>();
361             Logger.debug("dFilter", "waiting for synchronized block");
362             Logger.debug("dFilter", String.format(Locale.US,
363                     "entered synchronized block (about to examine %d accounts)", list.size()));
364             newDisplayed.add(new AccountListItem());    // header
365
366             int count = 0;
367             for (LedgerAccount a : list) {
368                 if (isInterrupted())
369                     return;
370
371                 if (a.isVisible()) {
372                     newDisplayed.add(new AccountListItem(a));
373                     count++;
374                 }
375             }
376             if (!isInterrupted()) {
377                 model.displayedAccounts.postValue(newDisplayed);
378                 Data.lastUpdateAccountCount.postValue(count);
379             }
380             Logger.debug("dFilter", "left synchronized block");
381         }
382     }
383
384     static class TransactionsDisplayedFilter extends Thread {
385         private final MainModel model;
386         private final List<LedgerTransaction> list;
387         TransactionsDisplayedFilter(MainModel model, List<LedgerTransaction> list) {
388             this.model = model;
389             this.list = list;
390         }
391         @Override
392         public void run() {
393             List<LedgerAccount> newDisplayed = new ArrayList<>();
394             Logger.debug("dFilter", "waiting for synchronized block");
395             Logger.debug("dFilter", String.format(Locale.US,
396                     "entered synchronized block (about to examine %d transactions)", list.size()));
397             String accNameFilter = model.getAccountFilter()
398                                         .getValue();
399
400             TransactionAccumulator acc = new TransactionAccumulator(model);
401             for (LedgerTransaction tr : list) {
402                 if (isInterrupted()) {
403                     return;
404                 }
405
406                 if (accNameFilter == null || tr.hasAccountNamedLike(accNameFilter)) {
407                     acc.put(tr, tr.getDate());
408                 }
409             }
410             if (!isInterrupted()) {
411                 acc.done();
412             }
413             Logger.debug("dFilter", "left synchronized block");
414         }
415     }
416 }