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