]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
833c038a26ef095e35f8ac397609a25e6b5b2f7a
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / MainActivity.java
1 /*
2  * Copyright © 2019 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.Intent;
21 import android.content.pm.PackageInfo;
22 import android.content.pm.ShortcutInfo;
23 import android.content.pm.ShortcutManager;
24 import android.content.res.ColorStateList;
25 import android.graphics.Color;
26 import android.graphics.drawable.Icon;
27 import android.os.AsyncTask;
28 import android.os.Build;
29 import android.os.Bundle;
30 import android.util.Log;
31 import android.view.View;
32 import android.view.ViewGroup;
33 import android.view.ViewPropertyAnimator;
34 import android.view.animation.Animation;
35 import android.view.animation.AnimationUtils;
36 import android.widget.LinearLayout;
37 import android.widget.ProgressBar;
38 import android.widget.TextView;
39 import android.widget.Toast;
40
41 import com.google.android.material.floatingactionbutton.FloatingActionButton;
42
43 import net.ktnx.mobileledger.R;
44 import net.ktnx.mobileledger.async.DbOpQueue;
45 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
46 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
47 import net.ktnx.mobileledger.model.Data;
48 import net.ktnx.mobileledger.model.LedgerAccount;
49 import net.ktnx.mobileledger.model.MobileLedgerProfile;
50 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryAdapter;
51 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
52 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryViewModel;
53 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
54 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
55 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
56 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
57 import net.ktnx.mobileledger.utils.Colors;
58 import net.ktnx.mobileledger.utils.LockHolder;
59 import net.ktnx.mobileledger.utils.MLDB;
60
61 import org.jetbrains.annotations.NotNull;
62
63 import java.lang.ref.WeakReference;
64 import java.text.DateFormat;
65 import java.util.ArrayList;
66 import java.util.Date;
67 import java.util.List;
68 import java.util.Observer;
69
70 import androidx.appcompat.app.ActionBarDrawerToggle;
71 import androidx.appcompat.widget.Toolbar;
72 import androidx.core.view.GravityCompat;
73 import androidx.drawerlayout.widget.DrawerLayout;
74 import androidx.fragment.app.Fragment;
75 import androidx.fragment.app.FragmentManager;
76 import androidx.fragment.app.FragmentPagerAdapter;
77 import androidx.recyclerview.widget.LinearLayoutManager;
78 import androidx.recyclerview.widget.RecyclerView;
79 import androidx.viewpager.widget.ViewPager;
80
81 public class MainActivity extends ProfileThemedActivity {
82     public static final String STATE_CURRENT_PAGE = "current_page";
83     public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
84     public static final String STATE_ACC_FILTER = "account_filter";
85     public AccountSummaryFragment mAccountSummaryFragment;
86     DrawerLayout drawer;
87     private LinearLayout profileListContainer;
88     private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
89     private LinearLayout profileListHeadMoreAndCancel;
90     private FragmentManager fragmentManager;
91     private TextView tvLastUpdate;
92     private RetrieveTransactionsTask retrieveTransactionsTask;
93     private View bTransactionListCancelDownload;
94     private ProgressBar progressBar;
95     private LinearLayout progressLayout;
96     private SectionsPagerAdapter mSectionsPagerAdapter;
97     private ViewPager mViewPager;
98     private FloatingActionButton fab;
99     private boolean profileModificationEnabled = false;
100     private boolean profileListExpanded = false;
101     private ProfilesRecyclerViewAdapter mProfileListAdapter;
102     private int mCurrentPage;
103     private String mAccountFilter;
104     private boolean mBackMeansToAccountList = false;
105     private Observer profileObserver;
106     private Observer profilesObserver;
107     private Toolbar mToolbar;
108     private DrawerLayout.SimpleDrawerListener drawerListener;
109     private ActionBarDrawerToggle barDrawerToggle;
110     private ViewPager.SimpleOnPageChangeListener pageChangeListener;
111     private Observer editingProfilesObserver;
112     @Override
113     protected void onStart() {
114         super.onStart();
115
116         Log.d("flow", "MainActivity.onStart()");
117         mViewPager.setCurrentItem(mCurrentPage, false);
118         if (mAccountFilter != null) showTransactionsFragment(mAccountFilter);
119         else Data.accountFilter.setValue(null);
120
121     }
122     @Override
123     protected void onSaveInstanceState(Bundle outState) {
124         super.onSaveInstanceState(outState);
125         outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
126         if (mAccountFilter != null)
127             outState.putString(STATE_ACC_FILTER, mAccountFilter);
128     }
129     @Override
130     protected void onDestroy() {
131         mSectionsPagerAdapter = null;
132         Data.profile.deleteObserver(profileObserver);
133         profileObserver = null;
134         Data.profiles.deleteObserver(profilesObserver);
135         profilesObserver = null;
136         RecyclerView root = findViewById(R.id.nav_profile_list);
137         if (root != null) root.setAdapter(null);
138         if (drawer != null) drawer.removeDrawerListener(drawerListener);
139         drawerListener = null;
140         if (drawer != null) drawer.removeDrawerListener(barDrawerToggle);
141         barDrawerToggle = null;
142         if (mViewPager != null) mViewPager.removeOnPageChangeListener(pageChangeListener);
143         pageChangeListener = null;
144         if (mProfileListAdapter != null)
145             mProfileListAdapter.deleteEditingProfilesObserver(editingProfilesObserver);
146         editingProfilesObserver = null;
147         super.onDestroy();
148     }
149     @Override
150     protected void onCreate(Bundle savedInstanceState) {
151         super.onCreate(savedInstanceState);
152         Log.d("flow", "MainActivity.onCreate()");
153         int profileColor = Data.retrieveCurrentThemeIdFromDb();
154         Colors.setupTheme(this, profileColor);
155         Colors.profileThemeId = profileColor;
156         setContentView(R.layout.activity_main);
157
158         fab = findViewById(R.id.btn_add_transaction);
159         profileListContainer = findViewById(R.id.nav_profile_list_container);
160         profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
161         profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
162         profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
163         profileListHeadMoreAndCancel = findViewById(R.id.nav_profile_list_head_buttons);
164         drawer = findViewById(R.id.drawer_layout);
165         tvLastUpdate = findViewById(R.id.transactions_last_update);
166         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
167         progressBar = findViewById(R.id.transaction_list_progress_bar);
168         progressLayout = findViewById(R.id.transaction_progress_layout);
169         fragmentManager = getSupportFragmentManager();
170         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
171         mViewPager = findViewById(R.id.root_frame);
172
173         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
174         if (extra != null && savedInstanceState == null) savedInstanceState = extra;
175
176
177         mToolbar = findViewById(R.id.toolbar);
178         setSupportActionBar(mToolbar);
179
180         if (profileObserver == null) {
181             profileObserver = (o, arg) -> onProfileChanged(arg);
182             Data.profile.addObserver(profileObserver);
183         }
184
185         if (profilesObserver == null) {
186             profilesObserver = (o, arg) -> onProfileListChanged(arg);
187             Data.profiles.addObserver(profilesObserver);
188         }
189
190         if (barDrawerToggle == null) {
191             barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
192                     R.string.navigation_drawer_open, R.string.navigation_drawer_close);
193             drawer.addDrawerListener(barDrawerToggle);
194         }
195         barDrawerToggle.syncState();
196
197         TextView ver = drawer.findViewById(R.id.drawer_version_text);
198
199         try {
200             PackageInfo pi =
201                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
202             ver.setText(pi.versionName);
203         }
204         catch (Exception e) {
205             e.printStackTrace();
206         }
207
208         if (progressBar == null)
209             throw new RuntimeException("Can't get hold on the transaction value progress bar");
210         if (progressLayout == null) throw new RuntimeException(
211                 "Can't get hold on the transaction value progress bar layout");
212
213         markDrawerItemCurrent(R.id.nav_account_summary);
214
215         mViewPager.setAdapter(mSectionsPagerAdapter);
216
217         if (pageChangeListener == null) {
218             pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
219                 @Override
220                 public void onPageSelected(int position) {
221                     switch (position) {
222                         case 0:
223                             markDrawerItemCurrent(R.id.nav_account_summary);
224                             break;
225                         case 1:
226                             markDrawerItemCurrent(R.id.nav_latest_transactions);
227                             break;
228                         default:
229                             Log.e("MainActivity",
230                                     String.format("Unexpected page index %d", position));
231                     }
232
233                     super.onPageSelected(position);
234                 }
235             };
236             mViewPager.addOnPageChangeListener(pageChangeListener);
237         }
238
239         mCurrentPage = 0;
240         if (savedInstanceState != null) {
241             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
242             if (currentPage != -1) {
243                 mCurrentPage = currentPage;
244             }
245             mAccountFilter = savedInstanceState.getString(STATE_ACC_FILTER, null);
246         }
247         else mAccountFilter = null;
248
249         Data.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
250
251         findViewById(R.id.btn_no_profiles_add)
252                 .setOnClickListener(v -> startEditProfileActivity(null));
253
254         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
255
256         findViewById(R.id.nav_new_profile_button)
257                 .setOnClickListener(v -> startEditProfileActivity(null));
258
259         RecyclerView root = findViewById(R.id.nav_profile_list);
260         if (root == null)
261             throw new RuntimeException("Can't get hold on the transaction value view");
262
263         if (mProfileListAdapter == null) mProfileListAdapter = new ProfilesRecyclerViewAdapter();
264         root.setAdapter(mProfileListAdapter);
265
266         if (editingProfilesObserver == null) {
267             editingProfilesObserver = (o, arg) -> {
268                 if (mProfileListAdapter.isEditingProfiles()) {
269                     profileListHeadArrow.clearAnimation();
270                     profileListHeadArrow.setVisibility(View.GONE);
271                     profileListHeadMore.setVisibility(View.GONE);
272                     profileListHeadCancel.setVisibility(View.VISIBLE);
273                 }
274                 else {
275                     profileListHeadArrow.setRotation(180f);
276                     profileListHeadArrow.setVisibility(View.VISIBLE);
277                     profileListHeadCancel.setVisibility(View.GONE);
278                     profileListHeadMore.setVisibility(View.GONE);
279                     profileListHeadMore
280                             .setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
281                 }
282             };
283             mProfileListAdapter.addEditingProfilesObserver(editingProfilesObserver);
284         }
285
286         LinearLayoutManager llm = new LinearLayoutManager(this);
287
288         llm.setOrientation(RecyclerView.VERTICAL);
289         root.setLayoutManager(llm);
290
291         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
292         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
293         profileListHeadMoreAndCancel
294                 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
295
296         if (drawerListener == null) {
297             drawerListener = new DrawerLayout.SimpleDrawerListener() {
298                 @Override
299                 public void onDrawerClosed(View drawerView) {
300                     super.onDrawerClosed(drawerView);
301                     collapseProfileList();
302                 }
303             };
304             drawer.addDrawerListener(drawerListener);
305         }
306
307         findViewById(R.id.nav_profile_list_head_layout)
308                 .setOnClickListener(this::navProfilesHeadClicked);
309         findViewById(R.id.nav_profiles_label).setOnClickListener(this::navProfilesHeadClicked);
310         setupProfile();
311         onProfileChanged(null);
312
313         updateLastUpdateTextFromDB();
314     }
315     private void scheduleDataRetrievalIfStale(Date lastUpdate) {
316         long now = new Date().getTime();
317         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
318             if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
319             else Log.d("db",
320                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
321                             lastUpdate.getTime() / 1000f, now / 1000f));
322
323             scheduleTransactionListRetrieval();
324         }
325     }
326     private void createShortcuts() {
327         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return;
328
329         List<ShortcutInfo> shortcuts = new ArrayList<>();
330         try (LockHolder lh = Data.profiles.lockForReading()) {
331             for (int i = 0; i < Data.profiles.size(); i++) {
332                 MobileLedgerProfile p = Data.profiles.get(i);
333                 if (!p.isPostingPermitted()) continue;
334
335                 ShortcutInfo si = new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid())
336                         .setShortLabel(p.getName())
337                         .setIcon(Icon.createWithResource(this, R.drawable.svg_thick_plus_white))
338                         .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
339                                 NewTransactionActivity.class).putExtra("profile_uuid", p.getUuid()))
340                         .setRank(i).build();
341                 shortcuts.add(si);
342             }
343         }
344         ShortcutManager sm = getSystemService(ShortcutManager.class);
345         sm.setDynamicShortcuts(shortcuts);
346     }
347     private void onProfileListChanged(Object arg) {
348         findViewById(R.id.nav_profile_list).setMinimumHeight(
349                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
350                        Data.profiles.size()));
351
352         Log.d("profiles", "profile list changed");
353         if (arg == null) mProfileListAdapter.notifyDataSetChanged();
354         else mProfileListAdapter.notifyItemChanged((int) arg);
355
356         createShortcuts();
357     }
358     private void onProfileChanged(Object arg) {
359         MobileLedgerProfile profile = Data.profile.get();
360         MainActivity.this.runOnUiThread(() -> {
361
362             boolean haveProfile = profile != null;
363             findViewById(R.id.no_profiles_layout)
364                     .setVisibility(haveProfile ? View.GONE : View.VISIBLE);
365             findViewById(R.id.pager_layout)
366                     .setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
367
368             Data.transactions.clear();
369             Log.d("transactions", "requesting list reload");
370             TransactionListViewModel.scheduleTransactionListReload();
371
372             Data.accounts.clear();
373             AccountSummaryViewModel.scheduleAccountListReload();
374
375             if (profile == null) MainActivity.this.setTitle(R.string.app_name);
376             else MainActivity.this.setTitle(profile.getName());
377             MainActivity.this.updateLastUpdateTextFromDB();
378             int old_index = -1;
379             int new_index = -1;
380             if (arg != null) {
381                 MobileLedgerProfile old = (MobileLedgerProfile) arg;
382                 old_index = Data.getProfileIndex(old);
383                 new_index = Data.getProfileIndex(profile);
384             }
385
386             if ((old_index != -1) && (new_index != -1)) {
387                 mProfileListAdapter.notifyItemChanged(old_index);
388                 mProfileListAdapter.notifyItemChanged(new_index);
389             }
390             else mProfileListAdapter.notifyDataSetChanged();
391
392             MainActivity.this.collapseProfileList();
393
394             int newProfileTheme = (profile == null) ? -1 : profile.getThemeId();
395             if (newProfileTheme != Colors.profileThemeId) {
396                 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
397                         newProfileTheme));
398                 MainActivity.this.profileThemeChanged();
399                 Colors.profileThemeId = newProfileTheme;
400                 // profileThemeChanged would restart the activity, so no need to reload the
401                 // data sets below
402                 return;
403             }
404             drawer.closeDrawers();
405
406             if (profile == null) {
407                 mToolbar.setSubtitle(null);
408                 fab.hide();
409             }
410             else {
411                 if (profile.isPostingPermitted()) {
412                     mToolbar.setSubtitle(null);
413                     fab.show();
414                 }
415                 else {
416                     mToolbar.setSubtitle(R.string.profile_subitlte_read_only);
417                     fab.hide();
418                 }
419             }
420
421             updateLastUpdateTextFromDB();
422         });
423     }
424     private void updateLastUpdateDisplay(Date newValue) {
425         LinearLayout l = findViewById(R.id.transactions_last_update_layout);
426         TextView v = findViewById(R.id.transactions_last_update);
427         if (newValue == null) {
428             l.setVisibility(View.INVISIBLE);
429             Log.d("main", "no last update date :(");
430         }
431         else {
432             final String text = DateFormat.getDateTimeInstance().format(newValue);
433             v.setText(text);
434             l.setVisibility(View.VISIBLE);
435             Log.d("main", String.format("Date formatted: %s", text));
436         }
437
438         scheduleDataRetrievalIfStale(newValue);
439     }
440     @Override
441     public void finish() {
442         if (profilesObserver != null) {
443             Data.profiles.deleteObserver(profilesObserver);
444             profilesObserver = null;
445         }
446
447         if (profileObserver != null) {
448             Data.profile.deleteObserver(profileObserver);
449             profileObserver = null;
450         }
451
452         super.finish();
453     }
454     private void profileThemeChanged() {
455         setupProfileColors();
456
457         Bundle bundle = new Bundle();
458         onSaveInstanceState(bundle);
459         // restart activity to reflect theme change
460         finish();
461         Intent intent = new Intent(this, this.getClass());
462         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
463         startActivity(intent);
464     }
465     public void startEditProfileActivity(MobileLedgerProfile profile) {
466         Intent intent = new Intent(this, ProfileDetailActivity.class);
467         Bundle args = new Bundle();
468         if (profile != null) {
469             int index = Data.getProfileIndex(profile);
470             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
471         }
472         intent.putExtras(args);
473         startActivity(intent, args);
474     }
475     private void setupProfile() {
476         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
477         MobileLedgerProfile profile;
478
479         profile = Data.getProfile(profileUUID);
480
481         if (Data.profiles.isEmpty()) {
482             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
483             findViewById(R.id.pager_layout).setVisibility(View.GONE);
484             return;
485         }
486
487         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
488         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
489
490         if (profile == null) profile = Data.profiles.get(0);
491
492         if (profile == null) throw new AssertionError("profile must have a value");
493
494         Data.setCurrentProfile(profile);
495     }
496     public void fabNewTransactionClicked(View view) {
497         Intent intent = new Intent(this, NewTransactionActivity.class);
498         startActivity(intent);
499         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
500     }
501     public void navSettingsClicked(View view) {
502         Intent intent = new Intent(this, SettingsActivity.class);
503         startActivity(intent);
504         drawer.closeDrawers();
505     }
506     public void markDrawerItemCurrent(int id) {
507         TextView item = drawer.findViewById(id);
508         item.setBackgroundColor(Colors.tableRowDarkBG);
509
510         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
511         for (int i = 0; i < actions.getChildCount(); i++) {
512             View view = actions.getChildAt(i);
513             if (view.getId() != id) {
514                 view.setBackgroundColor(Color.TRANSPARENT);
515             }
516         }
517     }
518     public void onAccountSummaryClicked(View view) {
519         drawer.closeDrawers();
520
521         showAccountSummaryFragment();
522     }
523     private void showAccountSummaryFragment() {
524         mViewPager.setCurrentItem(0, true);
525         Data.accountFilter.setValue(null);
526 //        FragmentTransaction ft = fragmentManager.beginTransaction();
527 //        accountSummaryFragment = new AccountSummaryFragment();
528 //        ft.replace(R.id.root_frame, accountSummaryFragment);
529 //        ft.commit();
530 //        currentFragment = accountSummaryFragment;
531     }
532     public void onLatestTransactionsClicked(View view) {
533         drawer.closeDrawers();
534
535         showTransactionsFragment((String) null);
536     }
537     private void resetFragmentBackStack() {
538 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
539     }
540     private void showTransactionsFragment(String accName) {
541         Data.accountFilter.setValue(accName);
542         mViewPager.setCurrentItem(1, true);
543     }
544     private void showTransactionsFragment(LedgerAccount account) {
545         showTransactionsFragment((account == null) ? (String) null : account.getName());
546 //        FragmentTransaction ft = fragmentManager.beginTransaction();
547 //        if (transactionListFragment == null) {
548 //            Log.d("flow", "MainActivity creating TransactionListFragment");
549 //            transactionListFragment = new TransactionListFragment();
550 //        }
551 //        Bundle bundle = new Bundle();
552 //        if (account != null) {
553 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
554 //                    account.getName());
555 //        }
556 //        transactionListFragment.setArguments(bundle);
557 //        ft.replace(R.id.root_frame, transactionListFragment);
558 //        if (account != null)
559 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
560 //        ft.commit();
561 //
562 //        currentFragment = transactionListFragment;
563     }
564     public void showAccountTransactions(LedgerAccount account) {
565         mBackMeansToAccountList = true;
566         showTransactionsFragment(account);
567     }
568     @Override
569     public void onBackPressed() {
570         DrawerLayout drawer = findViewById(R.id.drawer_layout);
571         if (drawer.isDrawerOpen(GravityCompat.START)) {
572             drawer.closeDrawer(GravityCompat.START);
573         }
574         else {
575             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
576                 Data.accountFilter.setValue(null);
577                 showAccountSummaryFragment();
578                 mBackMeansToAccountList = false;
579             }
580             else {
581                 Log.d("fragments", String.format("manager stack: %d",
582                         fragmentManager.getBackStackEntryCount()));
583
584                 super.onBackPressed();
585             }
586         }
587     }
588     public void updateLastUpdateTextFromDB() {
589         final MobileLedgerProfile profile = Data.profile.get();
590         long last_update = (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
591
592         Log.d("transactions", String.format("Last update = %d", last_update));
593         if (last_update == 0) {
594             Data.lastUpdateDate.postValue(null);
595         }
596         else {
597             Data.lastUpdateDate.postValue(new Date(last_update));
598         }
599     }
600     public void scheduleTransactionListRetrieval() {
601         if (Data.profile.get() == null) return;
602
603         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
604
605         retrieveTransactionsTask.execute();
606     }
607     public void onStopTransactionRefreshClick(View view) {
608         Log.d("interactive", "Cancelling transactions refresh");
609         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
610         bTransactionListCancelDownload.setEnabled(false);
611     }
612     public void onRetrieveDone(String error) {
613         progressLayout.setVisibility(View.GONE);
614
615         if (error == null) {
616             updateLastUpdateTextFromDB();
617
618             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
619             TransactionListViewModel.scheduleTransactionListReload();
620         }
621         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
622     }
623     public void onRetrieveStart() {
624         bTransactionListCancelDownload.setEnabled(true);
625         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
626         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
627         progressBar.setIndeterminate(true);
628         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
629         else progressBar.setProgress(0);
630         progressLayout.setVisibility(View.VISIBLE);
631     }
632     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
633         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
634             (progress.getTotal() == 0))
635         {
636             progressBar.setIndeterminate(true);
637         }
638         else {
639             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
640                 progressBar.setMin(0);
641             }
642             progressBar.setMax(progress.getTotal());
643             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
644                 progressBar.setProgress(progress.getProgress(), true);
645             }
646             else progressBar.setProgress(progress.getProgress());
647             progressBar.setIndeterminate(false);
648         }
649     }
650     public void fabShouldShow() {
651         MobileLedgerProfile profile = Data.profile.get();
652         if ((profile != null) && profile.isPostingPermitted()) fab.show();
653     }
654     public void navProfilesHeadClicked(View view) {
655         if (profileListExpanded) {
656             collapseProfileList();
657         }
658         else {
659             expandProfileList();
660         }
661     }
662     private void expandProfileList() {
663         profileListExpanded = true;
664
665
666         profileListContainer.setVisibility(View.VISIBLE);
667         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
668         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
669         profileListHeadMore.setVisibility(View.VISIBLE);
670         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
671         findViewById(R.id.nav_profile_list).setMinimumHeight(
672                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
673                        Data.profiles.size()));
674     }
675     private void collapseProfileList() {
676         profileListExpanded = false;
677
678         final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
679         animation.setAnimationListener(new Animation.AnimationListener() {
680             @Override
681             public void onAnimationStart(Animation animation) {
682
683             }
684             @Override
685             public void onAnimationEnd(Animation animation) {
686                 profileListContainer.setVisibility(View.GONE);
687             }
688             @Override
689             public void onAnimationRepeat(Animation animation) {
690
691             }
692         });
693         mProfileListAdapter.stopEditingProfiles();
694
695         profileListContainer.startAnimation(animation);
696         profileListHeadArrow.setRotation(0f);
697         profileListHeadArrow
698                 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
699         profileListHeadMore.setVisibility(View.GONE);
700     }
701     public void onAccountSummaryRowViewClicked(View view) {
702         ViewGroup row;
703         if (view.getId() == R.id.account_expander) row = (ViewGroup) view.getParent().getParent();
704         else row = (ViewGroup) view.getParent();
705
706         LedgerAccount acc = (LedgerAccount) row.getTag();
707         switch (view.getId()) {
708             case R.id.account_row_acc_name:
709             case R.id.account_expander:
710             case R.id.account_expander_container:
711                 Log.d("accounts", "Account expander clicked");
712                 if (!acc.hasSubAccounts()) return;
713
714                 boolean wasExpanded = acc.isExpanded();
715
716                 View arrow = row.findViewById(R.id.account_expander_container);
717
718                 arrow.clearAnimation();
719                 ViewPropertyAnimator animator = arrow.animate();
720
721                 acc.toggleExpanded();
722                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
723                         new Object[]{acc.isExpanded(), acc.getName(), Data.profile.get().getUuid()
724                         });
725
726                 if (wasExpanded) {
727                     Log.d("accounts", String.format("Collapsing account '%s'", acc.getName()));
728                     arrow.setRotation(0);
729                     animator.rotationBy(180);
730
731                     // removing all child accounts from the view
732                     int start = -1, count = 0;
733                     try (LockHolder lh = Data.accounts.lockForWriting()) {
734                         for (int i = 0; i < Data.accounts.size(); i++) {
735                             if (acc.isParentOf(Data.accounts.get(i))) {
736 //                                Log.d("accounts", String.format("Found a child '%s' at position %d",
737 //                                        Data.accounts.get(i).getName(), i));
738                                 if (start == -1) {
739                                     start = i;
740                                 }
741                                 count++;
742                             }
743                             else {
744                                 if (start != -1) {
745 //                                    Log.d("accounts",
746 //                                            String.format("Found a non-child '%s' at position %d",
747 //                                                    Data.accounts.get(i).getName(), i));
748                                     break;
749                                 }
750                             }
751                         }
752
753                         if (start != -1) {
754                             for (int j = 0; j < count; j++) {
755 //                                Log.d("accounts", String.format("Removing item %d: %s", start + j,
756 //                                        Data.accounts.get(start).getName()));
757                                 Data.accounts.removeQuietly(start);
758                             }
759
760                             mAccountSummaryFragment.modelAdapter
761                                     .notifyItemRangeRemoved(start, count);
762                         }
763                     }
764                 }
765                 else {
766                     Log.d("accounts", String.format("Expanding account '%s'", acc.getName()));
767                     arrow.setRotation(180);
768                     animator.rotationBy(-180);
769                     List<LedgerAccount> children =
770                             Data.profile.get().loadVisibleChildAccountsOf(acc);
771                     try (LockHolder lh = Data.accounts.lockForWriting()) {
772                         int parentPos = Data.accounts.indexOf(acc);
773                         if (parentPos != -1) {
774                             // may have disappeared in a concurrent refresh operation
775                             Data.accounts.addAllQuietly(parentPos + 1, children);
776                             mAccountSummaryFragment.modelAdapter
777                                     .notifyItemRangeInserted(parentPos + 1, children.size());
778                         }
779                     }
780                 }
781                 break;
782             case R.id.account_row_acc_amounts:
783                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
784                     acc.toggleAmountsExpanded();
785                     DbOpQueue
786                             .add("update accounts set amounts_expanded=? where name=? and profile=?",
787                                     new Object[]{acc.amountsExpanded(), acc.getName(),
788                                                  Data.profile.get().getUuid()
789                                     });
790                     Data.accounts.triggerItemChangedNotification(acc);
791                 }
792                 break;
793         }
794     }
795
796     public class SectionsPagerAdapter extends FragmentPagerAdapter {
797
798         public SectionsPagerAdapter(FragmentManager fm) {
799             super(fm);
800         }
801
802         @NotNull
803         @Override
804         public Fragment getItem(int position) {
805             Log.d("main", String.format("Switching to fragment %d", position));
806             switch (position) {
807                 case 0:
808 //                    Log.d("flow", "Creating account summary fragment");
809                     return mAccountSummaryFragment = new AccountSummaryFragment();
810                 case 1:
811                     return new TransactionListFragment();
812                 default:
813                     throw new IllegalStateException(
814                             String.format("Unexpected fragment index: " + "%d", position));
815             }
816         }
817
818         @Override
819         public int getCount() {
820             return 2;
821         }
822     }
823 }