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