]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
d5d0b71005b4cc48818fb55e0ddc8a521fc1969d
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / MainActivity.java
1 /*
2  * Copyright © 2021 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.activity;
19
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.pm.PackageInfo;
23 import android.content.pm.ShortcutInfo;
24 import android.content.pm.ShortcutManager;
25 import android.content.res.ColorStateList;
26 import android.graphics.Color;
27 import android.graphics.drawable.Icon;
28 import android.os.Build;
29 import android.os.Bundle;
30 import android.text.format.DateUtils;
31 import android.util.Log;
32 import android.view.View;
33 import android.view.animation.AnimationUtils;
34 import android.widget.TextView;
35
36 import androidx.annotation.NonNull;
37 import androidx.annotation.Nullable;
38 import androidx.appcompat.app.ActionBarDrawerToggle;
39 import androidx.appcompat.app.AlertDialog;
40 import androidx.core.view.GravityCompat;
41 import androidx.drawerlayout.widget.DrawerLayout;
42 import androidx.fragment.app.Fragment;
43 import androidx.fragment.app.FragmentActivity;
44 import androidx.lifecycle.LiveData;
45 import androidx.lifecycle.MutableLiveData;
46 import androidx.lifecycle.ViewModelProvider;
47 import androidx.recyclerview.widget.LinearLayoutManager;
48 import androidx.recyclerview.widget.RecyclerView;
49 import androidx.viewpager2.adapter.FragmentStateAdapter;
50 import androidx.viewpager2.widget.ViewPager2;
51
52 import com.google.android.material.snackbar.Snackbar;
53
54 import net.ktnx.mobileledger.R;
55 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
56 import net.ktnx.mobileledger.async.TransactionAccumulator;
57 import net.ktnx.mobileledger.databinding.ActivityMainBinding;
58 import net.ktnx.mobileledger.db.DB;
59 import net.ktnx.mobileledger.db.Option;
60 import net.ktnx.mobileledger.db.Profile;
61 import net.ktnx.mobileledger.db.TransactionWithAccounts;
62 import net.ktnx.mobileledger.model.Data;
63 import net.ktnx.mobileledger.model.LedgerTransaction;
64 import net.ktnx.mobileledger.ui.FabManager;
65 import net.ktnx.mobileledger.ui.MainModel;
66 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
67 import net.ktnx.mobileledger.ui.new_transaction.NewTransactionActivity;
68 import net.ktnx.mobileledger.ui.profiles.ProfileDetailActivity;
69 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
70 import net.ktnx.mobileledger.ui.templates.TemplatesActivity;
71 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
72 import net.ktnx.mobileledger.utils.Colors;
73 import net.ktnx.mobileledger.utils.Logger;
74 import net.ktnx.mobileledger.utils.Misc;
75
76 import org.jetbrains.annotations.NotNull;
77
78 import java.util.ArrayList;
79 import java.util.Date;
80 import java.util.List;
81 import java.util.Locale;
82 import java.util.Objects;
83
84 /*
85  * TODO: reports
86  *  */
87
88 public class MainActivity extends ProfileThemedActivity implements FabManager.FabHandler {
89     public static final String TAG = "main-act";
90     public static final String STATE_CURRENT_PAGE = "current_page";
91     public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
92     public static final String STATE_ACC_FILTER = "account_filter";
93     private static final boolean FAB_HIDDEN = false;
94     private static final boolean FAB_SHOWN = true;
95     private ConverterThread converterThread = null;
96     private SectionsPagerAdapter mSectionsPagerAdapter;
97     private ProfilesRecyclerViewAdapter mProfileListAdapter;
98     private int mCurrentPage;
99     private boolean mBackMeansToAccountList = false;
100     private DrawerLayout.SimpleDrawerListener drawerListener;
101     private ActionBarDrawerToggle barDrawerToggle;
102     private ViewPager2.OnPageChangeCallback pageChangeCallback;
103     private Profile profile;
104     private MainModel mainModel;
105     private ActivityMainBinding b;
106     private int fabVerticalOffset;
107     private FabManager fabManager;
108     @Override
109     protected void onStart() {
110         super.onStart();
111
112         Logger.debug(TAG, "onStart()");
113
114         b.mainPager.setCurrentItem(mCurrentPage, false);
115     }
116     @Override
117     protected void onSaveInstanceState(@NotNull Bundle outState) {
118         super.onSaveInstanceState(outState);
119         outState.putInt(STATE_CURRENT_PAGE, b.mainPager.getCurrentItem());
120         if (mainModel.getAccountFilter()
121                      .getValue() != null)
122             outState.putString(STATE_ACC_FILTER, mainModel.getAccountFilter()
123                                                           .getValue());
124     }
125     @Override
126     protected void onDestroy() {
127         mSectionsPagerAdapter = null;
128         b.navProfileList.setAdapter(null);
129         b.drawerLayout.removeDrawerListener(drawerListener);
130         drawerListener = null;
131         b.drawerLayout.removeDrawerListener(barDrawerToggle);
132         barDrawerToggle = null;
133         b.mainPager.unregisterOnPageChangeCallback(pageChangeCallback);
134         pageChangeCallback = null;
135         super.onDestroy();
136     }
137     @Override
138     protected void onResume() {
139         super.onResume();
140         fabShouldShow();
141     }
142     @Override
143     protected void onCreate(Bundle savedInstanceState) {
144         Logger.debug(TAG, "onCreate()/entry");
145         super.onCreate(savedInstanceState);
146         Logger.debug(TAG, "onCreate()/after super");
147         b = ActivityMainBinding.inflate(getLayoutInflater());
148         setContentView(b.getRoot());
149
150         mainModel = new ViewModelProvider(this).get(MainModel.class);
151
152         mSectionsPagerAdapter = new SectionsPagerAdapter(this);
153
154         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
155         if (extra != null && savedInstanceState == null)
156             savedInstanceState = extra;
157
158
159         setSupportActionBar(b.toolbar);
160
161         Data.observeProfile(this, this::onProfileChanged);
162
163         Data.profiles.observe(this, this::onProfileListChanged);
164
165         Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
166         Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
167
168         if (barDrawerToggle == null) {
169             barDrawerToggle = new ActionBarDrawerToggle(this, b.drawerLayout, b.toolbar,
170                     R.string.navigation_drawer_open, R.string.navigation_drawer_close);
171             b.drawerLayout.addDrawerListener(barDrawerToggle);
172         }
173         barDrawerToggle.syncState();
174
175         try {
176             PackageInfo pi = getApplicationContext().getPackageManager()
177                                                     .getPackageInfo(getPackageName(), 0);
178             ((TextView) b.navUpper.findViewById(R.id.drawer_version_text)).setText(pi.versionName);
179             ((TextView) b.noProfilesLayout.findViewById(R.id.drawer_version_text)).setText(
180                     pi.versionName);
181         }
182         catch (Exception e) {
183             e.printStackTrace();
184         }
185
186         markDrawerItemCurrent(R.id.nav_account_summary);
187
188         b.mainPager.setAdapter(mSectionsPagerAdapter);
189         b.mainPager.setOffscreenPageLimit(1);
190
191         if (pageChangeCallback == null) {
192             pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
193                 @Override
194                 public void onPageSelected(int position) {
195                     mCurrentPage = position;
196                     switch (position) {
197                         case 0:
198                             markDrawerItemCurrent(R.id.nav_account_summary);
199                             break;
200                         case 1:
201                             markDrawerItemCurrent(R.id.nav_latest_transactions);
202                             break;
203                         default:
204                             Log.e(TAG, String.format("Unexpected page index %d", position));
205                     }
206
207                     super.onPageSelected(position);
208                 }
209             };
210             b.mainPager.registerOnPageChangeCallback(pageChangeCallback);
211         }
212
213         mCurrentPage = 0;
214         if (savedInstanceState != null) {
215             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
216             if (currentPage != -1) {
217                 mCurrentPage = currentPage;
218             }
219             mainModel.getAccountFilter()
220                      .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
221         }
222
223         b.btnNoProfilesAdd.setOnClickListener(v -> ProfileDetailActivity.start(this, null));
224
225         b.btnAddTransaction.setOnClickListener(this::fabNewTransactionClicked);
226
227         b.navNewProfileButton.setOnClickListener(v -> ProfileDetailActivity.start(this, null));
228
229         b.transactionListCancelDownload.setOnClickListener(this::onStopTransactionRefreshClick);
230
231         if (mProfileListAdapter == null)
232             mProfileListAdapter = new ProfilesRecyclerViewAdapter();
233         b.navProfileList.setAdapter(mProfileListAdapter);
234
235         mProfileListAdapter.editingProfiles.observe(this, newValue -> {
236             if (newValue) {
237                 b.navProfilesStartEdit.setVisibility(View.GONE);
238                 b.navProfilesCancelEdit.setVisibility(View.VISIBLE);
239                 b.navNewProfileButton.setVisibility(View.VISIBLE);
240                 if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
241                     b.navProfilesStartEdit.startAnimation(
242                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
243                     b.navProfilesCancelEdit.startAnimation(
244                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
245                     b.navNewProfileButton.startAnimation(
246                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
247                 }
248             }
249             else {
250                 b.navProfilesCancelEdit.setVisibility(View.GONE);
251                 b.navProfilesStartEdit.setVisibility(View.VISIBLE);
252                 b.navNewProfileButton.setVisibility(View.GONE);
253                 if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
254                     b.navProfilesCancelEdit.startAnimation(
255                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
256                     b.navProfilesStartEdit.startAnimation(
257                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
258                     b.navNewProfileButton.startAnimation(
259                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
260                 }
261             }
262
263             mProfileListAdapter.notifyDataSetChanged();
264         });
265
266         fabManager = new FabManager(b.btnAddTransaction);
267
268         LinearLayoutManager llm = new LinearLayoutManager(this);
269
270         llm.setOrientation(RecyclerView.VERTICAL);
271         b.navProfileList.setLayoutManager(llm);
272
273         b.navProfilesStartEdit.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
274         b.navProfilesCancelEdit.setOnClickListener(
275                 (v) -> mProfileListAdapter.flipEditingProfiles());
276         b.navProfileListHeadButtons.setOnClickListener(
277                 (v) -> mProfileListAdapter.flipEditingProfiles());
278         if (drawerListener == null) {
279             drawerListener = new DrawerLayout.SimpleDrawerListener() {
280                 @Override
281                 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
282                     if (slideOffset > 0.2)
283                         fabManager.hideFab();
284                 }
285                 @Override
286                 public void onDrawerClosed(View drawerView) {
287                     super.onDrawerClosed(drawerView);
288                     mProfileListAdapter.setAnimationsEnabled(false);
289                     mProfileListAdapter.editingProfiles.setValue(false);
290                     Data.drawerOpen.setValue(false);
291                     fabShouldShow();
292                 }
293                 @Override
294                 public void onDrawerOpened(View drawerView) {
295                     super.onDrawerOpened(drawerView);
296                     mProfileListAdapter.setAnimationsEnabled(true);
297                     Data.drawerOpen.setValue(true);
298                     fabManager.hideFab();
299                 }
300             };
301             b.drawerLayout.addDrawerListener(drawerListener);
302         }
303
304         Data.drawerOpen.observe(this, open -> {
305             if (open)
306                 b.drawerLayout.open();
307             else
308                 b.drawerLayout.close();
309         });
310
311         mainModel.getUpdateError()
312                  .observe(this, (error) -> {
313                      if (error == null)
314                          return;
315
316                      Snackbar.make(b.mainPager, error, Snackbar.LENGTH_INDEFINITE)
317                              .show();
318                      mainModel.clearUpdateError();
319                  });
320         Data.locale.observe(this, l -> refreshLastUpdateInfo());
321         Data.lastUpdateDate.observe(this, date -> refreshLastUpdateInfo());
322         Data.lastUpdateTransactionCount.observe(this, date -> refreshLastUpdateInfo());
323         Data.lastUpdateAccountCount.observe(this, date -> refreshLastUpdateInfo());
324         b.navAccountSummary.setOnClickListener(this::onAccountSummaryClicked);
325         b.navLatestTransactions.setOnClickListener(this::onLatestTransactionsClicked);
326         b.navPatterns.setOnClickListener(this::onPatternsClick);
327     }
328     private void onPatternsClick(View view) {
329         Intent intent = new Intent(this, TemplatesActivity.class);
330         startActivity(intent);
331     }
332     private void scheduleDataRetrievalIfStale(long lastUpdate) {
333         long now = new Date().getTime();
334         if ((lastUpdate == 0) || (now > (lastUpdate + (24 * 3600 * 1000)))) {
335             if (lastUpdate == 0)
336                 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
337             else
338                 Logger.debug("db", String.format(Locale.ENGLISH,
339                         "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
340                         lastUpdate / 1000f, now / 1000f));
341
342             mainModel.scheduleTransactionListRetrieval();
343         }
344     }
345     private void createShortcuts(List<Profile> list) {
346         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
347             return;
348
349         ShortcutManager sm = getSystemService(ShortcutManager.class);
350         List<ShortcutInfo> shortcuts = new ArrayList<>();
351         int i = 0;
352         for (Profile p : list) {
353             if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
354                 break;
355
356             if (!p.permitPosting())
357                 continue;
358
359             final ShortcutInfo.Builder builder =
360                     new ShortcutInfo.Builder(this, "new_transaction_" + p.getId());
361             ShortcutInfo si = builder.setShortLabel(p.getName())
362                                      .setIcon(Icon.createWithResource(this,
363                                              R.drawable.thick_plus_icon))
364                                      .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
365                                              NewTransactionActivity.class).putExtra(
366                                              ProfileThemedActivity.PARAM_PROFILE_ID, p.getId())
367                                                                           .putExtra(
368                                                                                   ProfileThemedActivity.PARAM_THEME,
369                                                                                   p.getTheme()))
370                                      .setRank(i)
371                                      .build();
372             shortcuts.add(si);
373             i++;
374         }
375         sm.setDynamicShortcuts(shortcuts);
376     }
377     private void onProfileListChanged(List<Profile> newList) {
378         if ((newList == null) || newList.isEmpty()) {
379             b.noProfilesLayout.setVisibility(View.VISIBLE);
380             b.mainAppLayout.setVisibility(View.GONE);
381             return;
382         }
383
384         b.mainAppLayout.setVisibility(View.VISIBLE);
385         b.noProfilesLayout.setVisibility(View.GONE);
386
387         b.navProfileList.setMinimumHeight(
388                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
389
390         Logger.debug("profiles", "profile list changed");
391         mProfileListAdapter.setProfileList(newList);
392
393         createShortcuts(newList);
394
395         final Profile currentProfile = Data.getProfile();
396         Profile replacementProfile = null;
397         if (currentProfile != null) {
398             for (Profile p : newList) {
399                 if (p.getId() == currentProfile.getId()) {
400                     replacementProfile = p;
401                     break;
402                 }
403             }
404         }
405
406         if (replacementProfile == null) {
407             Logger.debug(TAG, "Switching profile because the current is no longer available");
408             Data.setCurrentProfile(newList.get(0));
409         }
410         else {
411             Data.setCurrentProfile(replacementProfile);
412         }
413     }
414     /**
415      * called when the current profile has changed
416      */
417     private void onProfileChanged(@Nullable Profile newProfile) {
418         if (this.profile != null) {
419             if (this.profile.equals(newProfile))
420                 return;
421         }
422
423         boolean haveProfile = newProfile != null;
424
425         if (haveProfile)
426             setTitle(newProfile.getName());
427         else
428             setTitle(R.string.app_name);
429
430         int newProfileTheme = haveProfile ? newProfile.getTheme() : Colors.DEFAULT_HUE_DEG;
431         if (newProfileTheme != Colors.profileThemeId) {
432             Logger.debug("profiles",
433                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
434                             newProfileTheme));
435             Colors.profileThemeId = newProfileTheme;
436             profileThemeChanged();
437             // profileThemeChanged would restart the activity, so no need to reload the
438             // data sets below
439             return;
440         }
441
442         final boolean sameProfileId = (newProfile != null) && (this.profile != null) &&
443                                       this.profile.getId() == newProfile.getId();
444
445         this.profile = newProfile;
446
447         b.noProfilesLayout.setVisibility(haveProfile ? View.GONE : View.VISIBLE);
448         b.pagerLayout.setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
449
450         mProfileListAdapter.notifyDataSetChanged();
451
452         if (haveProfile) {
453             if (newProfile.permitPosting()) {
454                 b.toolbar.setSubtitle(null);
455                 b.btnAddTransaction.show();
456             }
457             else {
458                 b.toolbar.setSubtitle(R.string.profile_subtitle_read_only);
459                 b.btnAddTransaction.hide();
460             }
461         }
462         else {
463             b.toolbar.setSubtitle(null);
464             b.btnAddTransaction.hide();
465         }
466
467         updateLastUpdateTextFromDB();
468
469         if (sameProfileId) {
470             Logger.debug(TAG, String.format(Locale.ROOT, "Short-cut profile 'changed' to %d",
471                     newProfile.getId()));
472             return;
473         }
474
475         mainModel.getAccountFilter()
476                  .observe(this, this::onAccountFilterChanged);
477
478         mainModel.stopTransactionsRetrieval();
479         mainModel.clearTransactions();
480     }
481     private void onAccountFilterChanged(String accFilter) {
482         Logger.debug(TAG, "account filter changed, reloading transactions");
483 //                     mainModel.scheduleTransactionListReload();
484         LiveData<List<TransactionWithAccounts>> transactions =
485                 new MutableLiveData<>(new ArrayList<>());
486         if (profile != null) {
487             if (accFilter == null || accFilter.isEmpty()) {
488                 transactions = DB.get()
489                                  .getTransactionDAO()
490                                  .getAllWithAccounts(profile.getId());
491             }
492             else {
493                 transactions = DB.get()
494                                  .getTransactionDAO()
495                                  .getAllWithAccountsFiltered(profile.getId(), accFilter);
496             }
497         }
498
499         transactions.observe(this, list -> {
500             Logger.debug(TAG,
501                     String.format(Locale.ROOT, "got transaction list from DB (%d transactions)",
502                             list.size()));
503
504             if (converterThread != null)
505                 converterThread.interrupt();
506             converterThread = new ConverterThread(mainModel, list, accFilter);
507             converterThread.start();
508         });
509     }
510     private void profileThemeChanged() {
511         // un-hook all observed LiveData
512         Data.removeProfileObservers(this);
513         Data.profiles.removeObservers(this);
514         Data.lastUpdateTransactionCount.removeObservers(this);
515         Data.lastUpdateAccountCount.removeObservers(this);
516         Data.lastUpdateDate.removeObservers(this);
517
518         Logger.debug(TAG, "profileThemeChanged(): recreating activity");
519         recreate();
520     }
521     public void fabNewTransactionClicked(View view) {
522         Intent intent = new Intent(this, NewTransactionActivity.class);
523         intent.putExtra(ProfileThemedActivity.PARAM_PROFILE_ID, profile.getId());
524         intent.putExtra(ProfileThemedActivity.PARAM_THEME, profile.getTheme());
525         startActivity(intent);
526         overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
527     }
528     public void markDrawerItemCurrent(int id) {
529         TextView item = b.drawerLayout.findViewById(id);
530         item.setBackgroundColor(Colors.tableRowDarkBG);
531
532         for (int i = 0; i < b.navActions.getChildCount(); i++) {
533             View view = b.navActions.getChildAt(i);
534             if (view.getId() != id) {
535                 view.setBackgroundColor(Color.TRANSPARENT);
536             }
537         }
538     }
539     public void onAccountSummaryClicked(View view) {
540         b.drawerLayout.closeDrawers();
541
542         showAccountSummaryFragment();
543     }
544     private void showAccountSummaryFragment() {
545         b.mainPager.setCurrentItem(0, true);
546         mainModel.getAccountFilter()
547                  .setValue(null);
548     }
549     public void onLatestTransactionsClicked(View view) {
550         b.drawerLayout.closeDrawers();
551
552         showTransactionsFragment(null);
553     }
554     public void showTransactionsFragment(String accName) {
555         mainModel.getAccountFilter()
556                  .setValue(accName);
557         b.mainPager.setCurrentItem(1, true);
558     }
559     public void showAccountTransactions(String accountName) {
560         mBackMeansToAccountList = true;
561         showTransactionsFragment(accountName);
562     }
563     @Override
564     public void onBackPressed() {
565         if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
566             b.drawerLayout.closeDrawer(GravityCompat.START);
567         }
568         else {
569             if (mBackMeansToAccountList && (b.mainPager.getCurrentItem() == 1)) {
570                 mainModel.getAccountFilter()
571                          .setValue(null);
572                 showAccountSummaryFragment();
573                 mBackMeansToAccountList = false;
574             }
575             else {
576                 Logger.debug(TAG, String.format(Locale.ENGLISH, "manager stack: %d",
577                         getSupportFragmentManager().getBackStackEntryCount()));
578
579                 super.onBackPressed();
580             }
581         }
582     }
583     public void updateLastUpdateTextFromDB() {
584         if (profile == null)
585             return;
586
587         DB.get()
588           .getOptionDAO()
589           .load(profile.getId(), Option.OPT_LAST_SCRAPE)
590           .observe(this, opt -> {
591               long lastUpdate = 0;
592               if (opt != null) {
593                   try {
594                       lastUpdate = Long.parseLong(opt.getValue());
595                   }
596                   catch (NumberFormatException ex) {
597                       Logger.debug(TAG, String.format("Error parsing '%s' as long", opt.getValue()),
598                               ex);
599                   }
600               }
601
602               if (lastUpdate == 0) {
603                   Data.lastUpdateDate.postValue(null);
604               }
605               else {
606                   Data.lastUpdateDate.postValue(new Date(lastUpdate));
607               }
608
609               scheduleDataRetrievalIfStale(lastUpdate);
610           });
611     }
612     private void refreshLastUpdateInfo() {
613         final int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
614                                 DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE;
615         String templateForTransactions =
616                 getResources().getString(R.string.transaction_count_summary);
617         String templateForAccounts = getResources().getString(R.string.account_count_summary);
618         Integer accountCount = Data.lastUpdateAccountCount.getValue();
619         Integer transactionCount = Data.lastUpdateTransactionCount.getValue();
620         Date lastUpdate = Data.lastUpdateDate.getValue();
621         if (lastUpdate == null) {
622             Data.lastTransactionsUpdateText.setValue("----");
623             Data.lastAccountsUpdateText.setValue("----");
624         }
625         else {
626             Data.lastTransactionsUpdateText.setValue(
627                     String.format(Objects.requireNonNull(Data.locale.getValue()),
628                             templateForTransactions,
629                             transactionCount == null ? 0 : transactionCount,
630                             DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
631             Data.lastAccountsUpdateText.setValue(
632                     String.format(Objects.requireNonNull(Data.locale.getValue()),
633                             templateForAccounts, accountCount == null ? 0 : accountCount,
634                             DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
635         }
636     }
637     public void onStopTransactionRefreshClick(View view) {
638         Logger.debug(TAG, "Cancelling transactions refresh");
639         mainModel.stopTransactionsRetrieval();
640         b.transactionListCancelDownload.setEnabled(false);
641     }
642     public void onRetrieveRunningChanged(Boolean running) {
643         if (running) {
644             b.transactionListCancelDownload.setEnabled(true);
645             ColorStateList csl = Colors.getColorStateList();
646             b.transactionListProgressBar.setIndeterminateTintList(csl);
647             b.transactionListProgressBar.setProgressTintList(csl);
648             b.transactionListProgressBar.setIndeterminate(true);
649             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
650                 b.transactionListProgressBar.setProgress(0, false);
651             }
652             else {
653                 b.transactionListProgressBar.setProgress(0);
654             }
655             b.transactionProgressLayout.setVisibility(View.VISIBLE);
656         }
657         else {
658             b.transactionProgressLayout.setVisibility(View.GONE);
659         }
660     }
661     public void onRetrieveProgress(@Nullable RetrieveTransactionsTask.Progress progress) {
662         if (progress == null ||
663             progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED)
664         {
665             Logger.debug(TAG, "progress: Done");
666             b.transactionProgressLayout.setVisibility(View.GONE);
667
668             mainModel.transactionRetrievalDone();
669
670             String error = (progress == null) ? null : progress.getError();
671             if (error != null) {
672                 if (error.equals(RetrieveTransactionsTask.Result.ERR_JSON_PARSER_ERROR))
673                     error = getResources().getString(R.string.err_json_parser_error);
674
675                 AlertDialog.Builder builder = new AlertDialog.Builder(this);
676                 builder.setMessage(error);
677                 builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
678                     Logger.debug(TAG, "will start profile editor");
679                     ProfileDetailActivity.start(this, profile);
680                 });
681                 builder.create()
682                        .show();
683                 return;
684             }
685
686             return;
687         }
688
689
690         b.transactionListCancelDownload.setEnabled(true);
691 //        ColorStateList csl = Colors.getColorStateList();
692 //        progressBar.setIndeterminateTintList(csl);
693 //        progressBar.setProgressTintList(csl);
694 //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
695 //            progressBar.setProgress(0, false);
696 //        else
697 //            progressBar.setProgress(0);
698         b.transactionProgressLayout.setVisibility(View.VISIBLE);
699
700         if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
701             b.transactionListProgressBar.setIndeterminate(true);
702             Logger.debug(TAG, "progress: indeterminate");
703         }
704         else {
705             if (b.transactionListProgressBar.isIndeterminate()) {
706                 b.transactionListProgressBar.setIndeterminate(false);
707             }
708 //            Logger.debug(TAG,
709 //                    String.format(Locale.US, "progress: %d/%d", progress.getProgress(),
710 //                    progress.getTotal
711 //                    ()));
712             b.transactionListProgressBar.setMax(progress.getTotal());
713             // for some reason animation doesn't work - no progress is shown (stick at 0)
714             // on lineageOS 14.1 (Nougat, 7.1.2)
715             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
716                 b.transactionListProgressBar.setProgress(progress.getProgress(), false);
717             else
718                 b.transactionListProgressBar.setProgress(progress.getProgress());
719         }
720     }
721     public void fabShouldShow() {
722         if ((profile != null) && profile.permitPosting() && !b.drawerLayout.isOpen())
723             fabManager.showFab();
724     }
725     @Override
726     public Context getContext() {
727         return this;
728     }
729     @Override
730     public void showManagedFab() {
731         fabShouldShow();
732     }
733     @Override
734     public void hideManagedFab() {
735         fabManager.hideFab();
736     }
737     public static class SectionsPagerAdapter extends FragmentStateAdapter {
738
739         public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
740             super(fragmentActivity);
741         }
742         @NotNull
743         @Override
744         public Fragment createFragment(int position) {
745             Logger.debug(TAG, String.format(Locale.ENGLISH, "Switching to fragment %d", position));
746             switch (position) {
747                 case 0:
748 //                    debug(TAG, "Creating account summary fragment");
749                     return new AccountSummaryFragment();
750                 case 1:
751                     return new TransactionListFragment();
752                 default:
753                     throw new IllegalStateException(
754                             String.format("Unexpected fragment index: " + "%d", position));
755             }
756         }
757
758         @Override
759         public int getItemCount() {
760             return 2;
761         }
762     }
763
764     static private class ConverterThread extends Thread {
765         private final List<TransactionWithAccounts> list;
766         private final MainModel model;
767         private final String accFilter;
768         public ConverterThread(@NonNull MainModel model,
769                                @NonNull List<TransactionWithAccounts> list, String accFilter) {
770             this.model = model;
771             this.list = list;
772             this.accFilter = accFilter;
773         }
774         @Override
775         public void run() {
776             TransactionAccumulator accumulator = new TransactionAccumulator(accFilter);
777
778             for (TransactionWithAccounts tr : list) {
779                 if (isInterrupted()) {
780                     Logger.debug(TAG, "ConverterThread bailing out on interrupt");
781                     return;
782                 }
783                 accumulator.put(new LedgerTransaction(tr));
784             }
785
786             if (isInterrupted()) {
787                 Logger.debug(TAG, "ConverterThread bailing out on interrupt");
788                 return;
789             }
790
791             Logger.debug(TAG, "ConverterThread publishing results");
792
793             Misc.onMainThread(() -> accumulator.publishResults(model));
794         }
795     }
796 }