]> git.ktnx.net Git - mobile-ledger.git/blobdiff - app/src/main/java/net/ktnx/mobileledger/ui/MainModel.java
adopt Room for displaying account lists
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / MainModel.java
index 5bc2554c4ff9b4f0db96824a6d017aca01891e00..aec736c48cca1a93dd7997e8b73160a4c5fe1837 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright © 2020 Damyan Ivanov.
+ * Copyright © 2021 Damyan Ivanov.
  * This file is part of MoLe.
  * MoLe is free software: you can distribute it and/or modify it
  * under the term of the GNU General Public License as published by
@@ -17,8 +17,6 @@
 
 package net.ktnx.mobileledger.ui;
 
-import android.database.Cursor;
-import android.database.sqlite.SQLiteDatabase;
 import android.os.AsyncTask;
 import android.os.Build;
 import android.text.TextUtils;
@@ -28,10 +26,10 @@ import androidx.lifecycle.LiveData;
 import androidx.lifecycle.MutableLiveData;
 import androidx.lifecycle.ViewModel;
 
-import net.ktnx.mobileledger.App;
 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
 import net.ktnx.mobileledger.async.TransactionAccumulator;
 import net.ktnx.mobileledger.async.UpdateTransactionsTask;
+import net.ktnx.mobileledger.model.AccountListItem;
 import net.ktnx.mobileledger.model.Data;
 import net.ktnx.mobileledger.model.LedgerAccount;
 import net.ktnx.mobileledger.model.LedgerTransaction;
@@ -55,22 +53,21 @@ import static net.ktnx.mobileledger.utils.Logger.debug;
 
 public class MainModel extends ViewModel {
     public final MutableLiveData<Integer> foundTransactionItemIndex = new MutableLiveData<>(null);
-    public final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>(null);
     private final MutableLiveData<Boolean> updatingFlag = new MutableLiveData<>(false);
     private final MutableLiveData<String> accountFilter = new MutableLiveData<>();
     private final MutableLiveData<List<TransactionListItem>> displayedTransactions =
             new MutableLiveData<>(new ArrayList<>());
-    private final MutableLiveData<List<LedgerAccount>> displayedAccounts = new MutableLiveData<>();
+    private final MutableLiveData<List<AccountListItem>> displayedAccounts =
+            new MutableLiveData<>();
     private final Locker accountsLocker = new Locker();
     private final MutableLiveData<String> updateError = new MutableLiveData<>();
+    private final Map<String, LedgerAccount> accountMap = new HashMap<>();
     private MobileLedgerProfile profile;
     private List<LedgerAccount> allAccounts = new ArrayList<>();
-    private final Map<String, LedgerAccount> accountMap = new HashMap<>();
     private SimpleDate firstTransactionDate;
     private SimpleDate lastTransactionDate;
     transient private RetrieveTransactionsTask retrieveTransactionsTask;
     transient private Thread displayedAccountsUpdater;
-    transient private AccountListLoader loader = null;
     private TransactionsDisplayedFilter displayedTransactionsUpdater;
     public static ArrayList<LedgerAccount> mergeAccountListsFromWeb(List<LedgerAccount> oldList,
                                                                     List<LedgerAccount> newList) {
@@ -123,11 +120,11 @@ public class MainModel extends ViewModel {
 
         return merged;
     }
-    private void setLastUpdateStamp() {
+    private void setLastUpdateStamp(long transactionCount) {
         debug("db", "Updating transaction value stamp");
         Date now = new Date();
         profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
-        lastUpdateDate.postValue(now);
+        Data.lastUpdateDate.postValue(now);
     }
     public void scheduleTransactionListReload() {
         UpdateTransactionsTask task = new UpdateTransactionsTask();
@@ -146,8 +143,9 @@ public class MainModel extends ViewModel {
     public LiveData<List<TransactionListItem>> getDisplayedTransactions() {
         return displayedTransactions;
     }
-    public void setDisplayedTransactions(List<TransactionListItem> list) {
+    public void setDisplayedTransactions(List<TransactionListItem> list, int transactionCount) {
         displayedTransactions.postValue(list);
+        Data.lastUpdateTransactionCount.postValue(transactionCount);
     }
     public SimpleDate getFirstTransactionDate() {
         return firstTransactionDate;
@@ -209,36 +207,20 @@ public class MainModel extends ViewModel {
             updateAccountsMap(allAccounts);
         }
     }
-    public LiveData<List<LedgerAccount>> getDisplayedAccounts() {
+    public LiveData<List<AccountListItem>> getDisplayedAccounts() {
         return displayedAccounts;
     }
-    synchronized public void scheduleAccountListReload() {
-        Logger.debug("async-acc", "scheduleAccountListReload() enter");
-        if ((loader != null) && loader.isAlive()) {
-            Logger.debug("async-acc", "returning early - loader already active");
-            return;
-        }
-
-        loader = new AccountListLoader(profile, this);
-        loader.start();
-    }
     public synchronized void setAndStoreAccountAndTransactionListFromWeb(
             List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
         profile.storeAccountAndTransactionListAsync(accounts, transactions);
 
-        setLastUpdateStamp();
+        setLastUpdateStamp(transactions.size());
 
         mergeAccountListFromWeb(accounts);
         updateDisplayedAccounts();
 
         updateDisplayedTransactionsFromWeb(transactions);
     }
-    synchronized public void abortAccountListReload() {
-        if (loader == null)
-            return;
-        loader.interrupt();
-        loader = null;
-    }
     synchronized public void updateDisplayedAccounts() {
         if (displayedAccountsUpdater != null) {
             displayedAccountsUpdater.interrupt();
@@ -269,83 +251,10 @@ public class MainModel extends ViewModel {
     public void clearUpdateError() {
         updateError.postValue(null);
     }
+    public void clearAccounts() { displayedAccounts.postValue(new ArrayList<>()); }
     public void clearTransactions() {
         displayedTransactions.setValue(new ArrayList<>());
     }
-
-    static class AccountListLoader extends Thread {
-        private final MobileLedgerProfile profile;
-        private final MainModel model;
-        AccountListLoader(MobileLedgerProfile profile, MainModel model) {
-            this.profile = profile;
-            this.model = model;
-        }
-        @Override
-        public void run() {
-            Logger.debug("async-acc", "AccountListLoader::run() entered");
-            String profileUUID = profile.getUuid();
-            ArrayList<LedgerAccount> list = new ArrayList<>();
-            HashMap<String, LedgerAccount> map = new HashMap<>();
-
-            String sql = "SELECT a.name, a.expanded, a.amounts_expanded";
-            sql += " from accounts a WHERE a.profile = ?";
-            sql += " ORDER BY a.name";
-
-            SQLiteDatabase db = App.getDatabase();
-            Logger.debug("async-acc", "AccountListLoader::run() connected to DB");
-            try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
-                Logger.debug("async-acc", "AccountListLoader::run() executed query");
-                while (cursor.moveToNext()) {
-                    if (isInterrupted())
-                        return;
-
-                    final String accName = cursor.getString(0);
-//                    debug("accounts",
-//                            String.format("Read account '%s' from DB [%s]", accName,
-//                            profileUUID));
-                    String parentName = LedgerAccount.extractParentName(accName);
-                    LedgerAccount parent;
-                    if (parentName != null) {
-                        parent = map.get(parentName);
-                        if (parent == null)
-                            throw new IllegalStateException(
-                                    String.format("Can't load account '%s': parent '%s' not loaded",
-                                            accName, parentName));
-                        parent.setHasSubAccounts(true);
-                    }
-                    else
-                        parent = null;
-
-                    LedgerAccount acc = new LedgerAccount(profile, accName, parent);
-                    acc.setExpanded(cursor.getInt(1) == 1);
-                    acc.setAmountsExpanded(cursor.getInt(2) == 1);
-                    acc.setHasSubAccounts(false);
-
-                    try (Cursor c2 = db.rawQuery(
-                            "SELECT value, currency FROM account_values WHERE profile = ?" + " " +
-                            "AND account = ?", new String[]{profileUUID, accName}))
-                    {
-                        while (c2.moveToNext()) {
-                            acc.addAmount(c2.getFloat(0), c2.getString(1));
-                        }
-                    }
-
-                    list.add(acc);
-                    map.put(accName, acc);
-                }
-                Logger.debug("async-acc", "AccountListLoader::run() query execution done");
-            }
-
-            if (isInterrupted())
-                return;
-
-            Logger.debug("async-acc", "AccountListLoader::run() posting new list");
-            model.allAccounts = list;
-            model.updateAccountsMap(list);
-            model.updateDisplayedAccounts();
-        }
-    }
-
     static class AccountListDisplayedFilter extends Thread {
         private final MainModel model;
         private final List<LedgerAccount> list;
@@ -355,21 +264,25 @@ public class MainModel extends ViewModel {
         }
         @Override
         public void run() {
-            List<LedgerAccount> newDisplayed = new ArrayList<>();
+            List<AccountListItem> newDisplayed = new ArrayList<>();
             Logger.debug("dFilter", "waiting for synchronized block");
             Logger.debug("dFilter", String.format(Locale.US,
                     "entered synchronized block (about to examine %d accounts)", list.size()));
+            newDisplayed.add(new AccountListItem.Header(Data.lastAccountsUpdateText));    // header
+
+            int count = 0;
             for (LedgerAccount a : list) {
-                if (isInterrupted()) {
+                if (isInterrupted())
                     return;
-                }
 
                 if (a.isVisible()) {
-                    newDisplayed.add(a);
+                    newDisplayed.add(new AccountListItem.Account(a));
+                    count++;
                 }
             }
             if (!isInterrupted()) {
                 model.displayedAccounts.postValue(newDisplayed);
+                Data.lastUpdateAccountCount.postValue(count);
             }
             Logger.debug("dFilter", "left synchronized block");
         }