]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
fc940e9ad6f8850b33e4ee9dd118dafc746e1ac3
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / MobileLedgerProfile.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.model;
19
20 import android.content.res.Resources;
21 import android.database.Cursor;
22 import android.database.sqlite.SQLiteDatabase;
23 import android.util.SparseArray;
24
25 import androidx.annotation.NonNull;
26 import androidx.annotation.Nullable;
27 import androidx.lifecycle.LiveData;
28 import androidx.lifecycle.MutableLiveData;
29
30 import net.ktnx.mobileledger.App;
31 import net.ktnx.mobileledger.R;
32 import net.ktnx.mobileledger.async.DbOpQueue;
33 import net.ktnx.mobileledger.async.SendTransactionTask;
34 import net.ktnx.mobileledger.utils.Logger;
35 import net.ktnx.mobileledger.utils.MLDB;
36 import net.ktnx.mobileledger.utils.Misc;
37
38 import java.util.ArrayList;
39 import java.util.Calendar;
40 import java.util.Date;
41 import java.util.List;
42 import java.util.Locale;
43 import java.util.UUID;
44
45 import static net.ktnx.mobileledger.utils.Logger.debug;
46
47 public final class MobileLedgerProfile {
48     // N.B. when adding new fields, update the copy-constructor below
49     private String uuid;
50     private String name;
51     private boolean permitPosting;
52     private boolean showCommentsByDefault;
53     private boolean showCommodityByDefault;
54     private String defaultCommodity;
55     private String preferredAccountsFilter;
56     private String url;
57     private boolean authEnabled;
58     private String authUserName;
59     private String authPassword;
60     private int themeHue;
61     private int orderNo = -1;
62     // N.B. when adding new fields, update the copy-constructor below
63     private FutureDates futureDates = FutureDates.None;
64     private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
65     private Calendar firstTransactionDate;
66     private Calendar lastTransactionDate;
67     private MutableLiveData<ArrayList<LedgerAccount>> accounts =
68             new MutableLiveData<>(new ArrayList<>());
69     private AccountListLoader loader = null;
70     public MobileLedgerProfile() {
71         this.uuid = String.valueOf(UUID.randomUUID());
72     }
73     public MobileLedgerProfile(String uuid) {
74         this.uuid = uuid;
75     }
76     public MobileLedgerProfile(MobileLedgerProfile origin) {
77         uuid = origin.uuid;
78         name = origin.name;
79         permitPosting = origin.permitPosting;
80         showCommentsByDefault = origin.showCommentsByDefault;
81         showCommodityByDefault = origin.showCommodityByDefault;
82         preferredAccountsFilter = origin.preferredAccountsFilter;
83         url = origin.url;
84         authEnabled = origin.authEnabled;
85         authUserName = origin.authUserName;
86         authPassword = origin.authPassword;
87         themeHue = origin.themeHue;
88         orderNo = origin.orderNo;
89         futureDates = origin.futureDates;
90         apiVersion = origin.apiVersion;
91         defaultCommodity = origin.defaultCommodity;
92         firstTransactionDate = origin.firstTransactionDate;
93         lastTransactionDate = origin.lastTransactionDate;
94     }
95     // loads all profiles into Data.profiles
96     // returns the profile with the given UUID
97     public static MobileLedgerProfile loadAllFromDB(@Nullable String currentProfileUUID) {
98         MobileLedgerProfile result = null;
99         ArrayList<MobileLedgerProfile> list = new ArrayList<>();
100         SQLiteDatabase db = App.getDatabase();
101         try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
102                                          "auth_password, permit_posting, theme, order_no, " +
103                                          "preferred_accounts_filter, future_dates, api_version, " +
104                                          "show_commodity_by_default, default_commodity, " +
105                                          "show_comments_by_default FROM " +
106                                          "profiles order by order_no", null))
107         {
108             while (cursor.moveToNext()) {
109                 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
110                 item.setName(cursor.getString(1));
111                 item.setUrl(cursor.getString(2));
112                 item.setAuthEnabled(cursor.getInt(3) == 1);
113                 item.setAuthUserName(cursor.getString(4));
114                 item.setAuthPassword(cursor.getString(5));
115                 item.setPostingPermitted(cursor.getInt(6) == 1);
116                 item.setThemeId(cursor.getInt(7));
117                 item.orderNo = cursor.getInt(8);
118                 item.setPreferredAccountsFilter(cursor.getString(9));
119                 item.setFutureDates(cursor.getInt(10));
120                 item.setApiVersion(cursor.getInt(11));
121                 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
122                 item.setDefaultCommodity(cursor.getString(13));
123                 item.setShowCommentsByDefault(cursor.getInt(14) == 1);
124                 list.add(item);
125                 if (item.getUuid()
126                         .equals(currentProfileUUID))
127                     result = item;
128             }
129         }
130         Data.profiles.setValue(list);
131         return result;
132     }
133     public static void storeProfilesOrder() {
134         SQLiteDatabase db = App.getDatabase();
135         db.beginTransactionNonExclusive();
136         try {
137             int orderNo = 0;
138             for (MobileLedgerProfile p : Data.profiles.getValue()) {
139                 db.execSQL("update profiles set order_no=? where uuid=?",
140                         new Object[]{orderNo, p.getUuid()});
141                 p.orderNo = orderNo;
142                 orderNo++;
143             }
144             db.setTransactionSuccessful();
145         }
146         finally {
147             db.endTransaction();
148         }
149     }
150     public LiveData<ArrayList<LedgerAccount>> getAccounts() {
151         return accounts;
152     }
153     synchronized public void scheduleAccountListReload() {
154         Logger.debug("async-acc", "scheduleAccountListReload() enter");
155         if ((loader != null) && loader.isAlive()) {
156             Logger.debug("async-acc", "returning early - loader already active");
157             return;
158         }
159
160         Logger.debug("async-acc", "Starting AccountListLoader");
161         loader = new AccountListLoader(this);
162         loader.start();
163     }
164     synchronized public void abortAccountListReload() {
165         if (loader == null)
166             return;
167         loader.interrupt();
168         loader = null;
169     }
170     public boolean getShowCommentsByDefault() {
171         return showCommentsByDefault;
172     }
173     public void setShowCommentsByDefault(boolean newValue) {
174         this.showCommentsByDefault = newValue;
175     }
176     public boolean getShowCommodityByDefault() {
177         return showCommodityByDefault;
178     }
179     public void setShowCommodityByDefault(boolean showCommodityByDefault) {
180         this.showCommodityByDefault = showCommodityByDefault;
181     }
182     public String getDefaultCommodity() {
183         return defaultCommodity;
184     }
185     public void setDefaultCommodity(String defaultCommodity) {
186         this.defaultCommodity = defaultCommodity;
187     }
188     public void setDefaultCommodity(CharSequence defaultCommodity) {
189         if (defaultCommodity == null)
190             this.defaultCommodity = null;
191         else
192             this.defaultCommodity = String.valueOf(defaultCommodity);
193     }
194     public SendTransactionTask.API getApiVersion() {
195         return apiVersion;
196     }
197     public void setApiVersion(SendTransactionTask.API apiVersion) {
198         this.apiVersion = apiVersion;
199     }
200     public void setApiVersion(int apiVersion) {
201         this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
202     }
203     public FutureDates getFutureDates() {
204         return futureDates;
205     }
206     public void setFutureDates(int anInt) {
207         futureDates = FutureDates.valueOf(anInt);
208     }
209     public void setFutureDates(FutureDates futureDates) {
210         this.futureDates = futureDates;
211     }
212     public String getPreferredAccountsFilter() {
213         return preferredAccountsFilter;
214     }
215     public void setPreferredAccountsFilter(String preferredAccountsFilter) {
216         this.preferredAccountsFilter = preferredAccountsFilter;
217     }
218     public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
219         setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
220     }
221     public boolean isPostingPermitted() {
222         return permitPosting;
223     }
224     public void setPostingPermitted(boolean permitPosting) {
225         this.permitPosting = permitPosting;
226     }
227     public String getUuid() {
228         return uuid;
229     }
230     public String getName() {
231         return name;
232     }
233     public void setName(CharSequence text) {
234         setName(String.valueOf(text));
235     }
236     public void setName(String name) {
237         this.name = name;
238     }
239     public String getUrl() {
240         return url;
241     }
242     public void setUrl(CharSequence text) {
243         setUrl(String.valueOf(text));
244     }
245     public void setUrl(String url) {
246         this.url = url;
247     }
248     public boolean isAuthEnabled() {
249         return authEnabled;
250     }
251     public void setAuthEnabled(boolean authEnabled) {
252         this.authEnabled = authEnabled;
253     }
254     public String getAuthUserName() {
255         return authUserName;
256     }
257     public void setAuthUserName(CharSequence text) {
258         setAuthUserName(String.valueOf(text));
259     }
260     public void setAuthUserName(String authUserName) {
261         this.authUserName = authUserName;
262     }
263     public String getAuthPassword() {
264         return authPassword;
265     }
266     public void setAuthPassword(CharSequence text) {
267         setAuthPassword(String.valueOf(text));
268     }
269     public void setAuthPassword(String authPassword) {
270         this.authPassword = authPassword;
271     }
272     public void storeInDB() {
273         SQLiteDatabase db = App.getDatabase();
274         db.beginTransactionNonExclusive();
275         try {
276 //            debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
277 //                                            "url=%s, permit_posting=%s, authEnabled=%s, " +
278 //                                            "themeHue=%d", uuid, name, url,
279 //                    permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
280             db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
281                        "use_authentication, auth_user, auth_password, theme, order_no, " +
282                        "preferred_accounts_filter, future_dates, api_version, " +
283                        "show_commodity_by_default, default_commodity, show_comments_by_default) " +
284                        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
285                     new Object[]{uuid, name, permitPosting, url, authEnabled,
286                                  authEnabled ? authUserName : null,
287                                  authEnabled ? authPassword : null, themeHue, orderNo,
288                                  preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
289                                  showCommodityByDefault, defaultCommodity, showCommentsByDefault
290                     });
291             db.setTransactionSuccessful();
292         }
293         finally {
294             db.endTransaction();
295         }
296     }
297     public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
298         // replace into is a bad idea because it would reset hidden to its default value
299         // we like the default, but for new accounts only
300         db.execSQL("update accounts set level = ?, keep = 1, expanded=? " +
301                    "where profile=? and name = ?",
302                 new Object[]{acc.getLevel(), acc.isExpanded(), uuid, acc.getName()
303                 });
304         db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, " +
305                    "expanded, keep) " + "select ?,?,?,?,?,?,1 where (select changes() = 0)",
306                 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
307                              acc.getLevel(), acc.isExpanded()
308                 });
309 //        debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
310     }
311     public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
312         db.execSQL("replace into account_values(profile, account, " +
313                    "currency, value, keep) values(?, ?, ?, ?, 1);",
314                 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount});
315     }
316     public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
317         tr.fillDataHash();
318         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
319                 new Object[]{uuid, tr.getId()});
320         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
321                 new Object[]{uuid, tr.getId()});
322
323         db.execSQL("INSERT INTO transactions(profile, id, year, month, day, description, " +
324                    "comment, data_hash, keep) values(?,?,?,?,?,?,?,?,1)",
325                 new Object[]{uuid, tr.getId(), tr.getDate().year, tr.getDate().month,
326                              tr.getDate().day, tr.getDescription(), tr.getComment(),
327                              tr.getDataHash()
328                 });
329
330         for (LedgerTransactionAccount item : tr.getAccounts()) {
331             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
332                        "account_name, amount, currency, comment) values(?, ?, ?, ?, ?, ?)",
333                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
334                                  Misc.nullIsEmpty(item.getCurrency()), item.getComment()
335                     });
336         }
337 //        debug("profile", String.format("Transaction %d stored", tr.getId()));
338     }
339     public String getOption(String name, String default_value) {
340         SQLiteDatabase db = App.getDatabase();
341         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
342                 new String[]{uuid, name}))
343         {
344             if (cursor.moveToFirst()) {
345                 String result = cursor.getString(0);
346
347                 if (result == null) {
348                     debug("profile", "returning default value for " + name);
349                     result = default_value;
350                 }
351                 else
352                     debug("profile", String.format("option %s=%s", name, result));
353
354                 return result;
355             }
356             else
357                 return default_value;
358         }
359         catch (Exception e) {
360             debug("db", "returning default value for " + name, e);
361             return default_value;
362         }
363     }
364     public long getLongOption(String name, long default_value) {
365         long longResult;
366         String result = getOption(name, "");
367         if ((result == null) || result.isEmpty()) {
368             debug("profile", String.format("Returning default value for option %s", name));
369             longResult = default_value;
370         }
371         else {
372             try {
373                 longResult = Long.parseLong(result);
374                 debug("profile", String.format("option %s=%s", name, result));
375             }
376             catch (Exception e) {
377                 debug("profile", String.format("Returning default value for option %s", name), e);
378                 longResult = default_value;
379             }
380         }
381
382         return longResult;
383     }
384     public void setOption(String name, String value) {
385         debug("profile", String.format("setting option %s=%s", name, value));
386         DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
387                 new String[]{uuid, name, value});
388     }
389     public void setLongOption(String name, long value) {
390         setOption(name, String.valueOf(value));
391     }
392     public void removeFromDB() {
393         SQLiteDatabase db = App.getDatabase();
394         debug("db", String.format("removing profile %s from DB", uuid));
395         db.beginTransactionNonExclusive();
396         try {
397             Object[] uuid_param = new Object[]{uuid};
398             db.execSQL("delete from profiles where uuid=?", uuid_param);
399             db.execSQL("delete from accounts where profile=?", uuid_param);
400             db.execSQL("delete from account_values where profile=?", uuid_param);
401             db.execSQL("delete from transactions where profile=?", uuid_param);
402             db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
403             db.execSQL("delete from options where profile=?", uuid_param);
404             db.setTransactionSuccessful();
405         }
406         finally {
407             db.endTransaction();
408         }
409     }
410     @NonNull
411     public LedgerAccount loadAccount(String name) {
412         SQLiteDatabase db = App.getDatabase();
413         return loadAccount(db, name);
414     }
415     @Nullable
416     public LedgerAccount tryLoadAccount(String acct_name) {
417         SQLiteDatabase db = App.getDatabase();
418         return tryLoadAccount(db, acct_name);
419     }
420     @NonNull
421     public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
422         LedgerAccount acc = tryLoadAccount(db, accName);
423
424         if (acc == null)
425             throw new RuntimeException("Unable to load account with name " + accName);
426
427         return acc;
428     }
429     @Nullable
430     public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
431         try (Cursor cursor = db.rawQuery("SELECT a.expanded, a.amounts_expanded, (select 1 from accounts a2 " +
432                                          "where a2.profile = a.profile and a2.name like a" +
433                                          ".name||':%' limit 1) " +
434                                          "FROM accounts a WHERE a.profile = ? and a.name=?",
435                 new String[]{uuid, accName}))
436         {
437             if (cursor.moveToFirst()) {
438                 LedgerAccount acc = new LedgerAccount(this, accName);
439                 acc.setExpanded(cursor.getInt(0) == 1);
440                 acc.setAmountsExpanded(cursor.getInt(1) == 1);
441                 acc.setHasSubAccounts(cursor.getInt(2) == 1);
442
443                 try (Cursor c2 = db.rawQuery(
444                         "SELECT value, currency FROM account_values WHERE profile = ? " +
445                         "AND account = ?", new String[]{uuid, accName}))
446                 {
447                     while (c2.moveToNext()) {
448                         acc.addAmount(c2.getFloat(0), c2.getString(1));
449                     }
450                 }
451
452                 return acc;
453             }
454             return null;
455         }
456     }
457     public LedgerTransaction loadTransaction(int transactionId) {
458         LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
459         tr.loadData(App.getDatabase());
460
461         return tr;
462     }
463     public int getThemeHue() {
464 //        debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
465         return this.themeHue;
466     }
467     public void setThemeHue(Object o) {
468         setThemeId(Integer.parseInt(String.valueOf(o)));
469     }
470     public void setThemeId(int themeHue) {
471 //        debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
472         this.themeHue = themeHue;
473     }
474     public void markTransactionsAsNotPresent(SQLiteDatabase db) {
475         db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
476
477     }
478     public void markAccountsAsNotPresent(SQLiteDatabase db) {
479         db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
480         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
481
482     }
483     public void deleteNotPresentAccounts(SQLiteDatabase db) {
484         db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
485         db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
486     }
487     public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
488         db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
489                 new Object[]{uuid, transaction.getId()
490                 });
491     }
492     public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
493                                                            LedgerTransaction transaction) {
494         db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
495                 new Object[]{uuid, transaction.getId()
496                 });
497
498     }
499     public void deleteNotPresentTransactions(SQLiteDatabase db) {
500         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
501     }
502     public void setLastUpdateStamp() {
503         debug("db", "Updating transaction value stamp");
504         Date now = new Date();
505         setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
506         Data.lastUpdateDate.postValue(now);
507     }
508     public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
509         List<LedgerAccount> result = new ArrayList<>();
510         SQLiteDatabase db = App.getDatabase();
511         try (Cursor c = db.rawQuery(
512                 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
513                 new String[]{uuid, acc.getName()}))
514         {
515             while (c.moveToNext()) {
516                 LedgerAccount a = loadAccount(db, c.getString(0));
517                 result.add(a);
518             }
519         }
520
521         return result;
522     }
523     public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
524         List<LedgerAccount> result = new ArrayList<>();
525         ArrayList<LedgerAccount> visibleList = new ArrayList<>();
526         visibleList.add(acc);
527
528         SQLiteDatabase db = App.getDatabase();
529         try (Cursor c = db.rawQuery(
530                 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
531                 new String[]{uuid, acc.getName()}))
532         {
533             while (c.moveToNext()) {
534                 LedgerAccount a = loadAccount(db, c.getString(0));
535                 if (a.isVisible(visibleList)) {
536                     result.add(a);
537                     visibleList.add(a);
538                 }
539             }
540         }
541
542         return result;
543     }
544     public void wipeAllData() {
545         SQLiteDatabase db = App.getDatabase();
546         db.beginTransaction();
547         try {
548             String[] pUuid = new String[]{uuid};
549             db.execSQL("delete from options where profile=?", pUuid);
550             db.execSQL("delete from accounts where profile=?", pUuid);
551             db.execSQL("delete from account_values where profile=?", pUuid);
552             db.execSQL("delete from transactions where profile=?", pUuid);
553             db.execSQL("delete from transaction_accounts where profile=?", pUuid);
554             db.setTransactionSuccessful();
555             debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
556         }
557         finally {
558             db.endTransaction();
559         }
560     }
561     public List<Currency> getCurrencies() {
562         SQLiteDatabase db = App.getDatabase();
563
564         ArrayList<Currency> result = new ArrayList<>();
565
566         try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
567                 new String[]{}))
568         {
569             while (c.moveToNext()) {
570                 Currency currency = new Currency(c.getInt(0), c.getString(1),
571                         Currency.Position.valueOf(c.getInt(2)), c.getInt(3) == 1);
572                 result.add(currency);
573             }
574         }
575
576         return result;
577     }
578     Currency loadCurrencyByName(String name) {
579         SQLiteDatabase db = App.getDatabase();
580         Currency result = tryLoadCurrencyByName(db, name);
581         if (result == null)
582             throw new RuntimeException(String.format("Unable to load currency '%s'", name));
583         return result;
584     }
585     private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
586         try (Cursor cursor = db.rawQuery(
587                 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
588                 new String[]{name}))
589         {
590             if (cursor.moveToFirst()) {
591                 return new Currency(cursor.getInt(0), cursor.getString(1),
592                         Currency.Position.valueOf(cursor.getInt(2)), cursor.getInt(3) == 1);
593             }
594             return null;
595         }
596     }
597     public Calendar getFirstTransactionDate() {
598         return firstTransactionDate;
599     }
600     public Calendar getLastTransactionDate() {
601         return lastTransactionDate;
602     }
603     public void setAccounts(ArrayList<LedgerAccount> list) {
604         accounts.postValue(list);
605     }
606     public enum FutureDates {
607         None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
608         SixMonths(180), OneYear(365), All(-1);
609         private static SparseArray<FutureDates> map = new SparseArray<>();
610
611         static {
612             for (FutureDates item : FutureDates.values()) {
613                 map.put(item.value, item);
614             }
615         }
616
617         private int value;
618         FutureDates(int value) {
619             this.value = value;
620         }
621         public static FutureDates valueOf(int i) {
622             return map.get(i, None);
623         }
624         public int toInt() {
625             return this.value;
626         }
627         public String getText(Resources resources) {
628             switch (value) {
629                 case 7:
630                     return resources.getString(R.string.future_dates_7);
631                 case 14:
632                     return resources.getString(R.string.future_dates_14);
633                 case 30:
634                     return resources.getString(R.string.future_dates_30);
635                 case 60:
636                     return resources.getString(R.string.future_dates_60);
637                 case 90:
638                     return resources.getString(R.string.future_dates_90);
639                 case 180:
640                     return resources.getString(R.string.future_dates_180);
641                 case 365:
642                     return resources.getString(R.string.future_dates_365);
643                 case -1:
644                     return resources.getString(R.string.future_dates_all);
645                 default:
646                     return resources.getString(R.string.future_dates_none);
647             }
648         }
649     }
650
651     static class AccountListLoader extends Thread {
652         MobileLedgerProfile profile;
653         AccountListLoader(MobileLedgerProfile profile) {
654             this.profile = profile;
655         }
656         @Override
657         public void run() {
658             Logger.debug("async-acc", "AccountListLoader::run() entered");
659             String profileUUID = profile.getUuid();
660             ArrayList<LedgerAccount> newList = new ArrayList<>();
661
662             String sql = "SELECT a.name from accounts a WHERE a.profile = ?";
663             sql += " ORDER BY a.name";
664
665             SQLiteDatabase db = App.getDatabase();
666             try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
667                 while (cursor.moveToNext()) {
668                     if (isInterrupted())
669                         return;
670
671                     final String accName = cursor.getString(0);
672 //                    debug("accounts",
673 //                            String.format("Read account '%s' from DB [%s]", accName,
674 //                            profileUUID));
675                     LedgerAccount acc = profile.loadAccount(db, accName);
676                     if (acc.isVisible(newList))
677                         newList.add(acc);
678                 }
679             }
680
681             if (isInterrupted())
682                 return;
683
684             Logger.debug("async-acc", "AccountListLoader::run() posting new list");
685             profile.accounts.postValue(newList);
686         }
687     }
688 }