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