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