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