]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
several fixes when there are no profiles after full room adoption
[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         Profile currentProfile = Data.getProfile();
396         boolean currentProfilePresent = false;
397         if (currentProfile != null) {
398             for (Profile p : newList) {
399                 if (p.getId() == currentProfile.getId()) {
400                     currentProfilePresent = true;
401                     break;
402                 }
403             }
404         }
405         if (!currentProfilePresent) {
406             Logger.debug(TAG, "Switching profile because the current is no longer available");
407             Data.setCurrentProfile(newList.get(0));
408         }
409     }
410     /**
411      * called when the current profile has changed
412      */
413     private void onProfileChanged(@Nullable Profile newProfile) {
414         if (this.profile != null) {
415             if (this.profile.equals(newProfile))
416                 return;
417         }
418
419         boolean haveProfile = newProfile != null;
420
421         if (haveProfile)
422             setTitle(newProfile.getName());
423         else
424             setTitle(R.string.app_name);
425
426         int newProfileTheme = haveProfile ? newProfile.getTheme() : Colors.DEFAULT_HUE_DEG;
427         if (newProfileTheme != Colors.profileThemeId) {
428             Logger.debug("profiles",
429                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
430                             newProfileTheme));
431             Colors.profileThemeId = newProfileTheme;
432             profileThemeChanged();
433             // profileThemeChanged would restart the activity, so no need to reload the
434             // data sets below
435             return;
436         }
437
438         final boolean sameProfileId = (newProfile != null) && (this.profile != null) &&
439                                       this.profile.getId() == newProfile.getId();
440
441         this.profile = newProfile;
442
443         b.noProfilesLayout.setVisibility(haveProfile ? View.GONE : View.VISIBLE);
444         b.pagerLayout.setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
445
446         mProfileListAdapter.notifyDataSetChanged();
447
448         if (haveProfile) {
449             if (newProfile.permitPosting()) {
450                 b.toolbar.setSubtitle(null);
451                 b.btnAddTransaction.show();
452             }
453             else {
454                 b.toolbar.setSubtitle(R.string.profile_subtitle_read_only);
455                 b.btnAddTransaction.hide();
456             }
457         }
458         else {
459             b.toolbar.setSubtitle(null);
460             b.btnAddTransaction.hide();
461         }
462
463         updateLastUpdateTextFromDB();
464
465         if (sameProfileId) {
466             Logger.debug(TAG, String.format(Locale.ROOT, "Short-cut profile 'changed' to %d",
467                     newProfile.getId()));
468             return;
469         }
470
471         mainModel.getAccountFilter()
472                  .observe(this, this::onAccountFilterChanged);
473
474         mainModel.stopTransactionsRetrieval();
475         mainModel.clearTransactions();
476     }
477     private void onAccountFilterChanged(String accFilter) {
478         Logger.debug(TAG, "account filter changed, reloading transactions");
479 //                     mainModel.scheduleTransactionListReload();
480         LiveData<List<TransactionWithAccounts>> transactions =
481                 new MutableLiveData<>(new ArrayList<>());
482         if (profile != null) {
483             if (accFilter == null || accFilter.isEmpty()) {
484                 transactions = DB.get()
485                                  .getTransactionDAO()
486                                  .getAllWithAccounts(profile.getId());
487             }
488             else {
489                 transactions = DB.get()
490                                  .getTransactionDAO()
491                                  .getAllWithAccountsFiltered(profile.getId(), accFilter);
492             }
493         }
494
495         transactions.observe(this, list -> {
496             Logger.debug(TAG,
497                     String.format(Locale.ROOT, "got transaction list from DB (%d transactions)",
498                             list.size()));
499
500             if (converterThread != null)
501                 converterThread.interrupt();
502             converterThread = new ConverterThread(mainModel, list, accFilter);
503             converterThread.start();
504         });
505     }
506     private void profileThemeChanged() {
507         // un-hook all observed LiveData
508         Data.removeProfileObservers(this);
509         Data.profiles.removeObservers(this);
510         Data.lastUpdateTransactionCount.removeObservers(this);
511         Data.lastUpdateAccountCount.removeObservers(this);
512         Data.lastUpdateDate.removeObservers(this);
513
514         Logger.debug(TAG, "profileThemeChanged(): recreating activity");
515         recreate();
516     }
517     public void fabNewTransactionClicked(View view) {
518         Intent intent = new Intent(this, NewTransactionActivity.class);
519         intent.putExtra(ProfileThemedActivity.PARAM_PROFILE_ID, profile.getId());
520         intent.putExtra(ProfileThemedActivity.PARAM_THEME, profile.getTheme());
521         startActivity(intent);
522         overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
523     }
524     public void markDrawerItemCurrent(int id) {
525         TextView item = b.drawerLayout.findViewById(id);
526         item.setBackgroundColor(Colors.tableRowDarkBG);
527
528         for (int i = 0; i < b.navActions.getChildCount(); i++) {
529             View view = b.navActions.getChildAt(i);
530             if (view.getId() != id) {
531                 view.setBackgroundColor(Color.TRANSPARENT);
532             }
533         }
534     }
535     public void onAccountSummaryClicked(View view) {
536         b.drawerLayout.closeDrawers();
537
538         showAccountSummaryFragment();
539     }
540     private void showAccountSummaryFragment() {
541         b.mainPager.setCurrentItem(0, true);
542         mainModel.getAccountFilter()
543                  .setValue(null);
544     }
545     public void onLatestTransactionsClicked(View view) {
546         b.drawerLayout.closeDrawers();
547
548         showTransactionsFragment(null);
549     }
550     public void showTransactionsFragment(String accName) {
551         mainModel.getAccountFilter()
552                  .setValue(accName);
553         b.mainPager.setCurrentItem(1, true);
554     }
555     public void showAccountTransactions(String accountName) {
556         mBackMeansToAccountList = true;
557         showTransactionsFragment(accountName);
558     }
559     @Override
560     public void onBackPressed() {
561         if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
562             b.drawerLayout.closeDrawer(GravityCompat.START);
563         }
564         else {
565             if (mBackMeansToAccountList && (b.mainPager.getCurrentItem() == 1)) {
566                 mainModel.getAccountFilter()
567                          .setValue(null);
568                 showAccountSummaryFragment();
569                 mBackMeansToAccountList = false;
570             }
571             else {
572                 Logger.debug(TAG, String.format(Locale.ENGLISH, "manager stack: %d",
573                         getSupportFragmentManager().getBackStackEntryCount()));
574
575                 super.onBackPressed();
576             }
577         }
578     }
579     public void updateLastUpdateTextFromDB() {
580         if (profile == null)
581             return;
582
583         DB.get()
584           .getOptionDAO()
585           .load(profile.getId(), Option.OPT_LAST_SCRAPE)
586           .observe(this, opt -> {
587               long lastUpdate = 0;
588               if (opt != null) {
589                   try {
590                       lastUpdate = Long.parseLong(opt.getValue());
591                   }
592                   catch (NumberFormatException ex) {
593                       Logger.debug(TAG, String.format("Error parsing '%s' as long", opt.getValue()),
594                               ex);
595                   }
596               }
597
598               if (lastUpdate == 0) {
599                   Data.lastUpdateDate.postValue(null);
600               }
601               else {
602                   Data.lastUpdateDate.postValue(new Date(lastUpdate));
603               }
604
605               scheduleDataRetrievalIfStale(lastUpdate);
606           });
607     }
608     private void refreshLastUpdateInfo() {
609         final int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
610                                 DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE;
611         String templateForTransactions =
612                 getResources().getString(R.string.transaction_count_summary);
613         String templateForAccounts = getResources().getString(R.string.account_count_summary);
614         Integer accountCount = Data.lastUpdateAccountCount.getValue();
615         Integer transactionCount = Data.lastUpdateTransactionCount.getValue();
616         Date lastUpdate = Data.lastUpdateDate.getValue();
617         if (lastUpdate == null) {
618             Data.lastTransactionsUpdateText.setValue("----");
619             Data.lastAccountsUpdateText.setValue("----");
620         }
621         else {
622             Data.lastTransactionsUpdateText.setValue(
623                     String.format(Objects.requireNonNull(Data.locale.getValue()),
624                             templateForTransactions,
625                             transactionCount == null ? 0 : transactionCount,
626                             DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
627             Data.lastAccountsUpdateText.setValue(
628                     String.format(Objects.requireNonNull(Data.locale.getValue()),
629                             templateForAccounts, accountCount == null ? 0 : accountCount,
630                             DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
631         }
632     }
633     public void onStopTransactionRefreshClick(View view) {
634         Logger.debug(TAG, "Cancelling transactions refresh");
635         mainModel.stopTransactionsRetrieval();
636         b.transactionListCancelDownload.setEnabled(false);
637     }
638     public void onRetrieveRunningChanged(Boolean running) {
639         if (running) {
640             b.transactionListCancelDownload.setEnabled(true);
641             ColorStateList csl = Colors.getColorStateList();
642             b.transactionListProgressBar.setIndeterminateTintList(csl);
643             b.transactionListProgressBar.setProgressTintList(csl);
644             b.transactionListProgressBar.setIndeterminate(true);
645             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
646                 b.transactionListProgressBar.setProgress(0, false);
647             }
648             else {
649                 b.transactionListProgressBar.setProgress(0);
650             }
651             b.transactionProgressLayout.setVisibility(View.VISIBLE);
652         }
653         else {
654             b.transactionProgressLayout.setVisibility(View.GONE);
655         }
656     }
657     public void onRetrieveProgress(@Nullable RetrieveTransactionsTask.Progress progress) {
658         if (progress == null ||
659             progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED)
660         {
661             Logger.debug(TAG, "progress: Done");
662             b.transactionProgressLayout.setVisibility(View.GONE);
663
664             mainModel.transactionRetrievalDone();
665
666             String error = (progress == null) ? null : progress.getError();
667             if (error != null) {
668                 if (error.equals(RetrieveTransactionsTask.Result.ERR_JSON_PARSER_ERROR))
669                     error = getResources().getString(R.string.err_json_parser_error);
670
671                 AlertDialog.Builder builder = new AlertDialog.Builder(this);
672                 builder.setMessage(error);
673                 builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
674                     Logger.debug(TAG, "will start profile editor");
675                     ProfileDetailActivity.start(this, profile);
676                 });
677                 builder.create()
678                        .show();
679                 return;
680             }
681
682             return;
683         }
684
685
686         b.transactionListCancelDownload.setEnabled(true);
687 //        ColorStateList csl = Colors.getColorStateList();
688 //        progressBar.setIndeterminateTintList(csl);
689 //        progressBar.setProgressTintList(csl);
690 //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
691 //            progressBar.setProgress(0, false);
692 //        else
693 //            progressBar.setProgress(0);
694         b.transactionProgressLayout.setVisibility(View.VISIBLE);
695
696         if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
697             b.transactionListProgressBar.setIndeterminate(true);
698             Logger.debug(TAG, "progress: indeterminate");
699         }
700         else {
701             if (b.transactionListProgressBar.isIndeterminate()) {
702                 b.transactionListProgressBar.setIndeterminate(false);
703             }
704 //            Logger.debug(TAG,
705 //                    String.format(Locale.US, "progress: %d/%d", progress.getProgress(),
706 //                    progress.getTotal
707 //                    ()));
708             b.transactionListProgressBar.setMax(progress.getTotal());
709             // for some reason animation doesn't work - no progress is shown (stick at 0)
710             // on lineageOS 14.1 (Nougat, 7.1.2)
711             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
712                 b.transactionListProgressBar.setProgress(progress.getProgress(), false);
713             else
714                 b.transactionListProgressBar.setProgress(progress.getProgress());
715         }
716     }
717     public void fabShouldShow() {
718         if ((profile != null) && profile.permitPosting() && !b.drawerLayout.isOpen())
719             fabManager.showFab();
720     }
721     @Override
722     public Context getContext() {
723         return this;
724     }
725     @Override
726     public void showManagedFab() {
727         fabShouldShow();
728     }
729     @Override
730     public void hideManagedFab() {
731         fabManager.hideFab();
732     }
733     public static class SectionsPagerAdapter extends FragmentStateAdapter {
734
735         public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
736             super(fragmentActivity);
737         }
738         @NotNull
739         @Override
740         public Fragment createFragment(int position) {
741             Logger.debug(TAG, String.format(Locale.ENGLISH, "Switching to fragment %d", position));
742             switch (position) {
743                 case 0:
744 //                    debug(TAG, "Creating account summary fragment");
745                     return new AccountSummaryFragment();
746                 case 1:
747                     return new TransactionListFragment();
748                 default:
749                     throw new IllegalStateException(
750                             String.format("Unexpected fragment index: " + "%d", position));
751             }
752         }
753
754         @Override
755         public int getItemCount() {
756             return 2;
757         }
758     }
759
760     static private class ConverterThread extends Thread {
761         private final List<TransactionWithAccounts> list;
762         private final MainModel model;
763         private final String accFilter;
764         public ConverterThread(@NonNull MainModel model,
765                                @NonNull List<TransactionWithAccounts> list, String accFilter) {
766             this.model = model;
767             this.list = list;
768             this.accFilter = accFilter;
769         }
770         @Override
771         public void run() {
772             TransactionAccumulator accumulator = new TransactionAccumulator(accFilter);
773
774             for (TransactionWithAccounts tr : list) {
775                 if (isInterrupted()) {
776                     Logger.debug(TAG, "ConverterThread bailing out on interrupt");
777                     return;
778                 }
779                 accumulator.put(new LedgerTransaction(tr));
780             }
781
782             if (isInterrupted()) {
783                 Logger.debug(TAG, "ConverterThread bailing out on interrupt");
784                 return;
785             }
786
787             Logger.debug(TAG, "ConverterThread publishing results");
788
789             Misc.onMainThread(() -> accumulator.publishResults(model));
790         }
791     }
792 }