]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
after showing account's transactions, make Back return to the account list
[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         TextView v = findViewById(R.id.transactions_last_update);
302         Date date = Data.lastUpdateDate.get();
303         if (date == null) {
304             v.setText(R.string.transaction_last_update_never);
305             Log.d("main", "no last update date :(");
306         }
307         else {
308             final String text = DateFormat.getDateTimeInstance().format(date);
309             v.setText(text);
310             Log.d("main", String.format("Date formatted: %s", text));
311         }
312     }
313     private void profileThemeChanged() {
314         setupProfileColors();
315
316         Bundle bundle = new Bundle();
317         onSaveInstanceState(bundle);
318         // restart activity to reflect theme change
319         finish();
320         Intent intent = new Intent(this, this.getClass());
321         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
322         startActivity(intent);
323     }
324     public void startEditProfileActivity(MobileLedgerProfile profile) {
325         Intent intent = new Intent(this, ProfileDetailActivity.class);
326         Bundle args = new Bundle();
327         if (profile != null) {
328             int index = Data.getProfileIndex(profile);
329             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
330         }
331         intent.putExtras(args);
332         startActivity(intent, args);
333     }
334     private void setupProfile() {
335         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
336         MobileLedgerProfile profile;
337
338         profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
339
340         if (Data.profiles.isEmpty()) {
341             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
342             findViewById(R.id.pager_layout).setVisibility(View.GONE);
343             return;
344         }
345
346         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
347         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
348
349         if (profile == null) profile = Data.profiles.get(0);
350
351         if (profile == null) throw new AssertionError("profile must have a value");
352
353         Data.setCurrentProfile(profile);
354     }
355     public void fabNewTransactionClicked(View view) {
356         Intent intent = new Intent(this, NewTransactionActivity.class);
357         startActivity(intent);
358         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
359     }
360     public void navSettingsClicked(View view) {
361         Intent intent = new Intent(this, SettingsActivity.class);
362         startActivity(intent);
363         drawer.closeDrawers();
364     }
365     public void markDrawerItemCurrent(int id) {
366         TextView item = drawer.findViewById(id);
367         item.setBackgroundColor(Colors.tableRowDarkBG);
368
369         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
370         for (int i = 0; i < actions.getChildCount(); i++) {
371             View view = actions.getChildAt(i);
372             if (view.getId() != id) {
373                 view.setBackgroundColor(Color.TRANSPARENT);
374             }
375         }
376     }
377     public void onAccountSummaryClicked(View view) {
378         drawer.closeDrawers();
379
380         showAccountSummaryFragment();
381     }
382     private void showAccountSummaryFragment() {
383         mViewPager.setCurrentItem(0, true);
384         TransactionListFragment.accountFilter.set(null);
385 //        FragmentTransaction ft = fragmentManager.beginTransaction();
386 //        accountSummaryFragment = new AccountSummaryFragment();
387 //        ft.replace(R.id.root_frame, accountSummaryFragment);
388 //        ft.commit();
389 //        currentFragment = accountSummaryFragment;
390     }
391     public void onLatestTransactionsClicked(View view) {
392         drawer.closeDrawers();
393
394         showTransactionsFragment((String) null);
395     }
396     private void resetFragmentBackStack() {
397 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
398     }
399     private void showTransactionsFragment(String accName) {
400         TransactionListFragment.accountFilter.set(accName);
401         TransactionListFragment.accountFilter.notifyObservers();
402         mViewPager.setCurrentItem(1, true);
403     }
404     private void showTransactionsFragment(LedgerAccount account) {
405         showTransactionsFragment((account == null) ? (String) null : account.getName());
406 //        FragmentTransaction ft = fragmentManager.beginTransaction();
407 //        if (transactionListFragment == null) {
408 //            Log.d("flow", "MainActivity creating TransactionListFragment");
409 //            transactionListFragment = new TransactionListFragment();
410 //        }
411 //        Bundle bundle = new Bundle();
412 //        if (account != null) {
413 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
414 //                    account.getName());
415 //        }
416 //        transactionListFragment.setArguments(bundle);
417 //        ft.replace(R.id.root_frame, transactionListFragment);
418 //        if (account != null)
419 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
420 //        ft.commit();
421 //
422 //        currentFragment = transactionListFragment;
423     }
424     public void showAccountTransactions(LedgerAccount account) {
425         mBackMeansToAccountList = true;
426         showTransactionsFragment(account);
427     }
428     @Override
429     public void onBackPressed() {
430         DrawerLayout drawer = findViewById(R.id.drawer_layout);
431         if (drawer.isDrawerOpen(GravityCompat.START)) {
432             drawer.closeDrawer(GravityCompat.START);
433         }
434         else {
435             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
436                 TransactionListFragment.accountFilter.set(null);
437                 showAccountSummaryFragment();
438                 mBackMeansToAccountList = false;
439             }
440             else {
441                 Log.d("fragments", String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
442
443                 super.onBackPressed();
444             }
445         }
446     }
447     public void updateLastUpdateTextFromDB() {
448         {
449             final MobileLedgerProfile profile = Data.profile.get();
450             long last_update =
451                     (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
452
453             Log.d("transactions", String.format("Last update = %d", last_update));
454             if (last_update == 0) {
455                 Data.lastUpdateDate.set(null);
456             }
457             else {
458                 Data.lastUpdateDate.set(new Date(last_update));
459             }
460         }
461     }
462     public void scheduleTransactionListRetrieval() {
463         if (Data.profile.get() == null) return;
464
465         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
466
467         retrieveTransactionsTask.execute();
468     }
469     public void onStopTransactionRefreshClick(View view) {
470         Log.d("interactive", "Cancelling transactions refresh");
471         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
472         bTransactionListCancelDownload.setEnabled(false);
473     }
474     public void onRetrieveDone(String error) {
475         progressLayout.setVisibility(View.GONE);
476
477         if (error == null) {
478             updateLastUpdateTextFromDB();
479
480             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
481             TransactionListViewModel.scheduleTransactionListReload();
482         }
483         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
484     }
485     public void onRetrieveStart() {
486         bTransactionListCancelDownload.setEnabled(true);
487         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
488         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
489         progressBar.setIndeterminate(true);
490         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
491         else progressBar.setProgress(0);
492         progressLayout.setVisibility(View.VISIBLE);
493     }
494     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
495         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
496             (progress.getTotal() == 0))
497         {
498             progressBar.setIndeterminate(true);
499         }
500         else {
501             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
502                 progressBar.setMin(0);
503             }
504             progressBar.setMax(progress.getTotal());
505             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
506                 progressBar.setProgress(progress.getProgress(), true);
507             }
508             else progressBar.setProgress(progress.getProgress());
509             progressBar.setIndeterminate(false);
510         }
511     }
512     public void fabShouldShow() {
513         MobileLedgerProfile profile = Data.profile.get();
514         if ((profile != null) && profile.isPostingPermitted()) fab.show();
515     }
516     public void navProfilesHeadClicked(View view) {
517         if (profileListExpanded) {
518             collapseProfileList();
519         }
520         else {
521             expandProfileList();
522         }
523     }
524     private void expandProfileList() {
525         profileListExpanded = true;
526
527
528         profileListContainer.setVisibility(View.VISIBLE);
529         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
530         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
531         profileListHeadMore.setVisibility(View.VISIBLE);
532         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
533         findViewById(R.id.nav_profile_list).setMinimumHeight(
534                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
535                        Data.profiles.size()));
536     }
537     private void collapseProfileList() {
538         profileListExpanded = false;
539
540         final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
541         animation.setAnimationListener(new Animation.AnimationListener() {
542             @Override
543             public void onAnimationStart(Animation animation) {
544
545             }
546             @Override
547             public void onAnimationEnd(Animation animation) {
548                 profileListContainer.setVisibility(View.GONE);
549             }
550             @Override
551             public void onAnimationRepeat(Animation animation) {
552
553             }
554         });
555         mProfileListAdapter.stopEditingProfiles();
556
557         profileListContainer.startAnimation(animation);
558         profileListHeadArrow.setRotation(0f);
559         profileListHeadArrow
560                 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
561         profileListHeadMore.setVisibility(View.GONE);
562     }
563     public void onProfileRowClicked(View v) {
564         Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
565     }
566     public void enableProfileModifications() {
567         profileModificationEnabled = true;
568         ViewGroup profileList = findViewById(R.id.nav_profile_list);
569         for (int i = 0; i < profileList.getChildCount(); i++) {
570             View aRow = profileList.getChildAt(i);
571             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
572             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
573         }
574         // FIXME enable rearranging
575
576     }
577     public void disableProfileModifications() {
578         profileModificationEnabled = false;
579         ViewGroup profileList = findViewById(R.id.nav_profile_list);
580         for (int i = 0; i < profileList.getChildCount(); i++) {
581             View aRow = profileList.getChildAt(i);
582             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
583             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
584         }
585         // FIXME disable rearranging
586
587     }
588     public void onAccountSummaryRowViewClicked(View view) {
589         ViewGroup row = (ViewGroup) view.getParent();
590         LedgerAccount acc = (LedgerAccount) row.getTag();
591         switch (view.getId()) {
592             case R.id.account_row_acc_name:
593             case R.id.account_expander_container:
594                 Log.d("accounts", "Account expander clicked");
595                 if (!acc.hasSubAccounts()) return;
596
597                 boolean wasExpanded = acc.isExpanded();
598
599                 View arrow = row.findViewById(R.id.account_expander_container);
600
601                 arrow.clearAnimation();
602                 ViewPropertyAnimator animator = arrow.animate();
603
604                 acc.toggleExpanded();
605                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
606                         new Object[]{acc.isExpanded(), acc.getName(), Data.profile.get().getUuid()
607                         });
608
609                 if (wasExpanded) {
610                     Log.d("accounts", String.format("Collapsing account '%s'", acc.getName()));
611                     arrow.setRotation(0);
612                     animator.rotationBy(180);
613
614                     // removing all child accounts from the view
615                     int start = -1, count = 0;
616                     try (LockHolder lh = Data.accounts.lockForWriting()) {
617                         for (int i = 0; i < Data.accounts.size(); i++) {
618                             if (acc.isParentOf(Data.accounts.get(i))) {
619 //                                Log.d("accounts", String.format("Found a child '%s' at position %d",
620 //                                        Data.accounts.get(i).getName(), i));
621                                 if (start == -1) {
622                                     start = i;
623                                 }
624                                 count++;
625                             }
626                             else {
627                                 if (start != -1) {
628 //                                    Log.d("accounts",
629 //                                            String.format("Found a non-child '%s' at position %d",
630 //                                                    Data.accounts.get(i).getName(), i));
631                                     break;
632                                 }
633                             }
634                         }
635
636                         if (start != -1) {
637                             for (int j = 0; j < count; j++) {
638 //                                Log.d("accounts", String.format("Removing item %d: %s", start + j,
639 //                                        Data.accounts.get(start).getName()));
640                                 Data.accounts.removeQuietly(start);
641                             }
642
643                             mAccountSummaryFragment.modelAdapter
644                                     .notifyItemRangeRemoved(start, count);
645                         }
646                     }
647                 }
648                 else {
649                     Log.d("accounts", String.format("Expanding account '%s'", acc.getName()));
650                     arrow.setRotation(180);
651                     animator.rotationBy(-180);
652                     List<LedgerAccount> children =
653                             Data.profile.get().loadVisibleChildAccountsOf(acc);
654                     try (LockHolder lh = Data.accounts.lockForWriting()) {
655                         int parentPos = Data.accounts.indexOf(acc);
656                         if (parentPos != -1) {
657                             // may have disappeared in a concurrent refresh operation
658                             Data.accounts.addAllQuietly(parentPos + 1, children);
659                             mAccountSummaryFragment.modelAdapter
660                                     .notifyItemRangeInserted(parentPos + 1, children.size());
661                         }
662                     }
663                 }
664                 break;
665             case R.id.account_row_acc_amounts:
666                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
667                     acc.toggleAmountsExpanded();
668                     DbOpQueue
669                             .add("update accounts set amounts_expanded=? where name=? and profile=?",
670                                     new Object[]{acc.amountsExpanded(), acc.getName(),
671                                                  Data.profile.get().getUuid()
672                                     });
673                     Data.accounts.triggerItemChangedNotification(acc);
674                 }
675                 break;
676         }
677     }
678
679     public class SectionsPagerAdapter extends FragmentPagerAdapter {
680
681         public SectionsPagerAdapter(FragmentManager fm) {
682             super(fm);
683         }
684
685         @Override
686         public Fragment getItem(int position) {
687             Log.d("main", String.format("Switching to fragment %d", position));
688             switch (position) {
689                 case 0:
690 //                    Log.d("flow", "Creating account summary fragment");
691                     return mAccountSummaryFragment = new AccountSummaryFragment();
692                 case 1:
693                     return new TransactionListFragment();
694                 default:
695                     throw new IllegalStateException(
696                             String.format("Unexpected fragment index: " + "%d", position));
697             }
698         }
699
700         @Override
701         public int getCount() {
702             return 2;
703         }
704     }
705 }