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