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