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