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.
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.
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/>.
18 package net.ktnx.mobileledger.ui;
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;
26 import androidx.annotation.Nullable;
27 import androidx.lifecycle.LiveData;
28 import androidx.lifecycle.MutableLiveData;
29 import androidx.lifecycle.ViewModel;
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.Data;
36 import net.ktnx.mobileledger.model.LedgerAccount;
37 import net.ktnx.mobileledger.model.LedgerTransaction;
38 import net.ktnx.mobileledger.model.MobileLedgerProfile;
39 import net.ktnx.mobileledger.model.TransactionListItem;
40 import net.ktnx.mobileledger.utils.LockHolder;
41 import net.ktnx.mobileledger.utils.Locker;
42 import net.ktnx.mobileledger.utils.Logger;
43 import net.ktnx.mobileledger.utils.MLDB;
44 import net.ktnx.mobileledger.utils.SimpleDate;
46 import java.util.ArrayList;
47 import java.util.Date;
48 import java.util.HashMap;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Locale;
54 import static net.ktnx.mobileledger.utils.Logger.debug;
56 public class MainModel extends ViewModel {
57 public final MutableLiveData<Integer> foundTransactionItemIndex = new MutableLiveData<>(null);
58 public final MutableLiveData<Date> lastUpdateDate = 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<LedgerAccount>> displayedAccounts = new MutableLiveData<>();
64 private final Locker accountsLocker = new Locker();
65 private final MutableLiveData<String> updateError = new MutableLiveData<>();
66 private MobileLedgerProfile profile;
67 private List<LedgerAccount> allAccounts = new ArrayList<>();
68 private final Map<String, LedgerAccount> accountMap = new HashMap<>();
69 private SimpleDate firstTransactionDate;
70 private SimpleDate lastTransactionDate;
71 transient private RetrieveTransactionsTask retrieveTransactionsTask;
72 transient private Thread displayedAccountsUpdater;
73 transient private AccountListLoader loader = null;
74 private TransactionsDisplayedFilter displayedTransactionsUpdater;
75 public static ArrayList<LedgerAccount> mergeAccountListsFromWeb(List<LedgerAccount> oldList,
76 List<LedgerAccount> newList) {
77 LedgerAccount oldAcc, newAcc;
78 ArrayList<LedgerAccount> merged = new ArrayList<>();
80 Iterator<LedgerAccount> oldIterator = oldList.iterator();
81 Iterator<LedgerAccount> newIterator = newList.iterator();
84 if (!oldIterator.hasNext()) {
85 // the rest of the incoming are new
86 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
87 newIterator.forEachRemaining(merged::add);
90 while (newIterator.hasNext())
91 merged.add(newIterator.next());
95 oldAcc = oldIterator.next();
97 if (!newIterator.hasNext()) {
98 // no more incoming accounts. ignore the rest of the old
101 newAcc = newIterator.next();
103 // ignore now missing old items
105 .compareTo(newAcc.getName()) < 0)
108 // add newly found items
110 .compareTo(newAcc.getName()) > 0)
116 // two items with same account names; forward-merge UI-controlled fields
117 // it is important that the result list contains a new LedgerAccount instance
118 // so that the change is propagated to the UI
119 newAcc.setExpanded(oldAcc.isExpanded());
120 newAcc.setAmountsExpanded(oldAcc.amountsExpanded());
126 private void setLastUpdateStamp() {
127 debug("db", "Updating transaction value stamp");
128 Date now = new Date();
129 profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
130 lastUpdateDate.postValue(now);
132 public void scheduleTransactionListReload() {
133 UpdateTransactionsTask task = new UpdateTransactionsTask();
134 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this);
136 public LiveData<Boolean> getUpdatingFlag() {
139 public LiveData<String> getUpdateError() {
142 public void setProfile(MobileLedgerProfile profile) {
143 stopTransactionsRetrieval();
144 this.profile = profile;
146 public LiveData<List<TransactionListItem>> getDisplayedTransactions() {
147 return displayedTransactions;
149 public void setDisplayedTransactions(List<TransactionListItem> list) {
150 displayedTransactions.postValue(list);
152 public SimpleDate getFirstTransactionDate() {
153 return firstTransactionDate;
155 public void setFirstTransactionDate(SimpleDate earliestDate) {
156 this.firstTransactionDate = earliestDate;
158 public MutableLiveData<String> getAccountFilter() {
159 return accountFilter;
161 public SimpleDate getLastTransactionDate() {
162 return lastTransactionDate;
164 public void setLastTransactionDate(SimpleDate latestDate) {
165 this.lastTransactionDate = latestDate;
167 private void applyTransactionFilter(List<LedgerTransaction> list) {
168 final String accFilter = accountFilter.getValue();
169 ArrayList<TransactionListItem> newList = new ArrayList<>();
171 TransactionAccumulator accumulator = new TransactionAccumulator(this);
172 if (TextUtils.isEmpty(accFilter))
173 for (LedgerTransaction tr : list)
174 newList.add(new TransactionListItem(tr));
176 for (LedgerTransaction tr : list)
177 if (tr.hasAccountNamedLike(accFilter))
178 newList.add(new TransactionListItem(tr));
180 displayedTransactions.postValue(newList);
182 public synchronized void scheduleTransactionListRetrieval() {
183 if (retrieveTransactionsTask != null) {
184 Logger.debug("db", "Ignoring request for transaction retrieval - already active");
187 MobileLedgerProfile profile = Data.getProfile();
189 retrieveTransactionsTask = new RetrieveTransactionsTask(this, profile, allAccounts);
190 Logger.debug("db", "Created a background transaction retrieval task");
192 retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
194 public synchronized void stopTransactionsRetrieval() {
195 if (retrieveTransactionsTask != null)
196 retrieveTransactionsTask.cancel(true);
198 public void transactionRetrievalDone() {
199 retrieveTransactionsTask = null;
201 public synchronized Locker lockAccountsForWriting() {
202 accountsLocker.lockForWriting();
203 return accountsLocker;
205 public void mergeAccountListFromWeb(List<LedgerAccount> newList) {
207 try (LockHolder l = accountsLocker.lockForWriting()) {
208 allAccounts = mergeAccountListsFromWeb(allAccounts, newList);
209 updateAccountsMap(allAccounts);
212 public LiveData<List<LedgerAccount>> getDisplayedAccounts() {
213 return displayedAccounts;
215 synchronized public void scheduleAccountListReload() {
216 Logger.debug("async-acc", "scheduleAccountListReload() enter");
217 if ((loader != null) && loader.isAlive()) {
218 Logger.debug("async-acc", "returning early - loader already active");
222 loader = new AccountListLoader(profile, this);
225 public synchronized void setAndStoreAccountAndTransactionListFromWeb(
226 List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
227 profile.storeAccountAndTransactionListAsync(accounts, transactions);
229 setLastUpdateStamp();
231 mergeAccountListFromWeb(accounts);
232 updateDisplayedAccounts();
234 updateDisplayedTransactionsFromWeb(transactions);
236 synchronized public void abortAccountListReload() {
242 synchronized public void updateDisplayedAccounts() {
243 if (displayedAccountsUpdater != null) {
244 displayedAccountsUpdater.interrupt();
246 displayedAccountsUpdater = new AccountListDisplayedFilter(this, allAccounts);
247 displayedAccountsUpdater.start();
249 synchronized public void updateDisplayedTransactionsFromWeb(List<LedgerTransaction> list) {
250 if (displayedTransactionsUpdater != null) {
251 displayedTransactionsUpdater.interrupt();
253 displayedTransactionsUpdater = new TransactionsDisplayedFilter(this, list);
254 displayedTransactionsUpdater.start();
256 public List<LedgerAccount> getAllAccounts() {
259 private void updateAccountsMap(List<LedgerAccount> newAccounts) {
261 for (LedgerAccount acc : newAccounts) {
262 accountMap.put(acc.getName(), acc);
266 public LedgerAccount locateAccount(String name) {
267 return accountMap.get(name);
269 public void clearUpdateError() {
270 updateError.postValue(null);
272 public void clearTransactions() {
273 displayedTransactions.setValue(new ArrayList<>());
276 static class AccountListLoader extends Thread {
277 private final MobileLedgerProfile profile;
278 private final MainModel model;
279 AccountListLoader(MobileLedgerProfile profile, MainModel model) {
280 this.profile = profile;
285 Logger.debug("async-acc", "AccountListLoader::run() entered");
286 String profileUUID = profile.getUuid();
287 ArrayList<LedgerAccount> list = new ArrayList<>();
288 HashMap<String, LedgerAccount> map = new HashMap<>();
290 String sql = "SELECT a.name, a.expanded, a.amounts_expanded";
291 sql += " from accounts a WHERE a.profile = ?";
292 sql += " ORDER BY a.name";
294 SQLiteDatabase db = App.getDatabase();
295 Logger.debug("async-acc", "AccountListLoader::run() connected to DB");
296 try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
297 Logger.debug("async-acc", "AccountListLoader::run() executed query");
298 while (cursor.moveToNext()) {
302 final String accName = cursor.getString(0);
304 // String.format("Read account '%s' from DB [%s]", accName,
306 String parentName = LedgerAccount.extractParentName(accName);
307 LedgerAccount parent;
308 if (parentName != null) {
309 parent = map.get(parentName);
311 throw new IllegalStateException(
312 String.format("Can't load account '%s': parent '%s' not loaded",
313 accName, parentName));
314 parent.setHasSubAccounts(true);
319 LedgerAccount acc = new LedgerAccount(profile, accName, parent);
320 acc.setExpanded(cursor.getInt(1) == 1);
321 acc.setAmountsExpanded(cursor.getInt(2) == 1);
322 acc.setHasSubAccounts(false);
324 try (Cursor c2 = db.rawQuery(
325 "SELECT value, currency FROM account_values WHERE profile = ?" + " " +
326 "AND account = ?", new String[]{profileUUID, accName}))
328 while (c2.moveToNext()) {
329 acc.addAmount(c2.getFloat(0), c2.getString(1));
334 map.put(accName, acc);
336 Logger.debug("async-acc", "AccountListLoader::run() query execution done");
342 Logger.debug("async-acc", "AccountListLoader::run() posting new list");
343 model.allAccounts = list;
344 model.updateAccountsMap(list);
345 model.updateDisplayedAccounts();
349 static class AccountListDisplayedFilter extends Thread {
350 private final MainModel model;
351 private final List<LedgerAccount> list;
352 AccountListDisplayedFilter(MainModel model, List<LedgerAccount> list) {
358 List<LedgerAccount> newDisplayed = new ArrayList<>();
359 Logger.debug("dFilter", "waiting for synchronized block");
360 Logger.debug("dFilter", String.format(Locale.US,
361 "entered synchronized block (about to examine %d accounts)", list.size()));
362 for (LedgerAccount a : list) {
363 if (isInterrupted()) {
371 if (!isInterrupted()) {
372 model.displayedAccounts.postValue(newDisplayed);
374 Logger.debug("dFilter", "left synchronized block");
378 static class TransactionsDisplayedFilter extends Thread {
379 private final MainModel model;
380 private final List<LedgerTransaction> list;
381 TransactionsDisplayedFilter(MainModel model, List<LedgerTransaction> list) {
387 List<LedgerAccount> newDisplayed = new ArrayList<>();
388 Logger.debug("dFilter", "waiting for synchronized block");
389 Logger.debug("dFilter", String.format(Locale.US,
390 "entered synchronized block (about to examine %d transactions)", list.size()));
391 String accNameFilter = model.getAccountFilter()
394 TransactionAccumulator acc = new TransactionAccumulator(model);
395 for (LedgerTransaction tr : list) {
396 if (isInterrupted()) {
400 if (accNameFilter == null || tr.hasAccountNamedLike(accNameFilter)) {
401 acc.put(tr, tr.getDate());
404 if (!isInterrupted()) {
407 Logger.debug("dFilter", "left synchronized block");