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