]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
move setupProfile from onCreate to onStart
[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(() -> {
220                 Date date = Data.lastUpdateDate.get();
221                 if (date == null) {
222                     tvLastUpdate.setText(R.string.transaction_last_update_never);
223                 }
224                 else {
225                     final String text = DateFormat.getDateTimeInstance().format(date);
226                     tvLastUpdate.setText(text);
227                     Log.d("despair", String.format("Date formatted: %s", text));
228                 }
229             });
230         });
231
232         findViewById(R.id.btn_no_profiles_add)
233                 .setOnClickListener(v -> startEditProfileActivity(null));
234
235         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
236
237         findViewById(R.id.nav_new_profile_button)
238                 .setOnClickListener(v -> startEditProfileActivity(null));
239
240         RecyclerView root = findViewById(R.id.nav_profile_list);
241         if (root == null)
242             throw new RuntimeException("Can't get hold on the transaction value view");
243
244         mProfileListAdapter = new ProfilesRecyclerViewAdapter();
245         root.setAdapter(mProfileListAdapter);
246
247         mProfileListAdapter.addEditingProfilesObserver(new Observer() {
248             @Override
249             public void update(Observable o, Object arg) {
250                 if (mProfileListAdapter.isEditingProfiles()) {
251                     profileListHeadArrow.clearAnimation();
252                     profileListHeadArrow.setVisibility(View.GONE);
253                     profileListHeadMore.setVisibility(View.GONE);
254                     profileListHeadCancel.setVisibility(View.VISIBLE);
255                 }
256                 else {
257                     profileListHeadArrow.setRotation(180f);
258                     profileListHeadArrow.setVisibility(View.VISIBLE);
259                     profileListHeadCancel.setVisibility(View.GONE);
260                     profileListHeadMore.setVisibility(View.GONE);
261                     profileListHeadMore
262                             .setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
263                 }
264             }
265         });
266
267         LinearLayoutManager llm = new LinearLayoutManager(this);
268
269         llm.setOrientation(RecyclerView.VERTICAL);
270         root.setLayoutManager(llm);
271
272         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
273         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
274         profileListHeadMoreAndCancel
275                 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
276
277         drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
278             @Override
279             public void onDrawerClosed(View drawerView) {
280                 super.onDrawerClosed(drawerView);
281                 collapseProfileList();
282             }
283         });
284     }
285     private void profileThemeChanged() {
286         setupProfileColors();
287
288         Bundle bundle = new Bundle();
289         onSaveInstanceState(bundle);
290         // restart activity to reflect theme change
291         finish();
292         Intent intent = new Intent(this, this.getClass());
293         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
294         startActivity(intent);
295     }
296     public void startEditProfileActivity(MobileLedgerProfile profile) {
297         Intent intent = new Intent(this, ProfileDetailActivity.class);
298         Bundle args = new Bundle();
299         if (profile != null) {
300             int index = Data.getProfileIndex(profile);
301             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
302         }
303         intent.putExtras(args);
304         startActivity(intent, args);
305     }
306     private void setupProfile() {
307         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
308         MobileLedgerProfile profile;
309
310         profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
311
312         if (Data.profiles.getList().isEmpty()) {
313             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
314             findViewById(R.id.pager_layout).setVisibility(View.GONE);
315             return;
316         }
317
318         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
319         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
320
321         if (profile == null) profile = Data.profiles.get(0);
322
323         if (profile == null) throw new AssertionError("profile must have a value");
324
325         Data.setCurrentProfile(profile);
326     }
327     public void fabNewTransactionClicked(View view) {
328         Intent intent = new Intent(this, NewTransactionActivity.class);
329         startActivity(intent);
330         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
331     }
332     public void navSettingsClicked(View view) {
333         Intent intent = new Intent(this, SettingsActivity.class);
334         startActivity(intent);
335         drawer.closeDrawers();
336     }
337     public void markDrawerItemCurrent(int id) {
338         TextView item = drawer.findViewById(id);
339         item.setBackgroundColor(Colors.tableRowDarkBG);
340
341         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
342         for (int i = 0; i < actions.getChildCount(); i++) {
343             View view = actions.getChildAt(i);
344             if (view.getId() != id) {
345                 view.setBackgroundColor(Color.TRANSPARENT);
346             }
347         }
348     }
349     public void onAccountSummaryClicked(View view) {
350         drawer.closeDrawers();
351
352         showAccountSummaryFragment();
353     }
354     private void showAccountSummaryFragment() {
355         mViewPager.setCurrentItem(0, true);
356         TransactionListFragment.accountFilter.set(null);
357 //        FragmentTransaction ft = fragmentManager.beginTransaction();
358 //        accountSummaryFragment = new AccountSummaryFragment();
359 //        ft.replace(R.id.root_frame, accountSummaryFragment);
360 //        ft.commit();
361 //        currentFragment = accountSummaryFragment;
362     }
363     public void onLatestTransactionsClicked(View view) {
364         drawer.closeDrawers();
365
366         showTransactionsFragment(null);
367     }
368     private void resetFragmentBackStack() {
369 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
370     }
371     private void showTransactionsFragment(LedgerAccount account) {
372         if (account != null) TransactionListFragment.accountFilter.set(account.getName());
373         mViewPager.setCurrentItem(1, true);
374 //        FragmentTransaction ft = fragmentManager.beginTransaction();
375 //        if (transactionListFragment == null) {
376 //            Log.d("flow", "MainActivity creating TransactionListFragment");
377 //            transactionListFragment = new TransactionListFragment();
378 //        }
379 //        Bundle bundle = new Bundle();
380 //        if (account != null) {
381 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
382 //                    account.getName());
383 //        }
384 //        transactionListFragment.setArguments(bundle);
385 //        ft.replace(R.id.root_frame, transactionListFragment);
386 //        if (account != null)
387 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
388 //        ft.commit();
389 //
390 //        currentFragment = transactionListFragment;
391     }
392     public void showAccountTransactions(LedgerAccount account) {
393         showTransactionsFragment(account);
394     }
395     @Override
396     public void onBackPressed() {
397         DrawerLayout drawer = findViewById(R.id.drawer_layout);
398         if (drawer.isDrawerOpen(GravityCompat.START)) {
399             drawer.closeDrawer(GravityCompat.START);
400         }
401         else {
402             Log.d("fragments",
403                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
404
405             super.onBackPressed();
406         }
407     }
408     public void updateLastUpdateTextFromDB() {
409         {
410             final MobileLedgerProfile profile = Data.profile.get();
411             long last_update =
412                     (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
413
414             Log.d("transactions", String.format("Last update = %d", last_update));
415             if (last_update == 0) {
416                 Data.lastUpdateDate.set(null);
417             }
418             else {
419                 Data.lastUpdateDate.set(new Date(last_update));
420             }
421         }
422     }
423     public void scheduleTransactionListRetrieval() {
424         if (Data.profile.get() == null) return;
425
426         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
427
428         retrieveTransactionsTask.execute();
429     }
430     public void onStopTransactionRefreshClick(View view) {
431         Log.d("interactive", "Cancelling transactions refresh");
432         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
433         bTransactionListCancelDownload.setEnabled(false);
434     }
435     public void onRetrieveDone(String error) {
436         progressLayout.setVisibility(View.GONE);
437
438         if (error == null) {
439             updateLastUpdateTextFromDB();
440
441             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
442             TransactionListViewModel.scheduleTransactionListReload();
443         }
444         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
445     }
446     public void onRetrieveStart() {
447         bTransactionListCancelDownload.setEnabled(true);
448         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
449         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
450         progressBar.setIndeterminate(true);
451         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
452         else progressBar.setProgress(0);
453         progressLayout.setVisibility(View.VISIBLE);
454     }
455     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
456         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
457             (progress.getTotal() == 0))
458         {
459             progressBar.setIndeterminate(true);
460         }
461         else {
462             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
463                 progressBar.setMin(0);
464             }
465             progressBar.setMax(progress.getTotal());
466             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
467                 progressBar.setProgress(progress.getProgress(), true);
468             }
469             else progressBar.setProgress(progress.getProgress());
470             progressBar.setIndeterminate(false);
471         }
472     }
473     public void fabShouldShow() {
474         MobileLedgerProfile profile = Data.profile.get();
475         if ((profile != null) && profile.isPostingPermitted()) fab.show();
476     }
477     public void navProfilesHeadClicked(View view) {
478         if (profileListExpanded) {
479             collapseProfileList();
480         }
481         else {
482             expandProfileList();
483         }
484     }
485     private void expandProfileList() {
486         profileListExpanded = true;
487
488
489         profileListContainer.setVisibility(View.VISIBLE);
490         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
491         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
492         profileListHeadMore.setVisibility(View.VISIBLE);
493         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
494         findViewById(R.id.nav_profile_list).setMinimumHeight(
495                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
496                        Data.profiles.size()));
497     }
498     private void collapseProfileList() {
499         profileListExpanded = false;
500
501         final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
502         animation.setAnimationListener(new Animation.AnimationListener() {
503             @Override
504             public void onAnimationStart(Animation animation) {
505
506             }
507             @Override
508             public void onAnimationEnd(Animation animation) {
509                 profileListContainer.setVisibility(View.GONE);
510             }
511             @Override
512             public void onAnimationRepeat(Animation animation) {
513
514             }
515         });
516         mProfileListAdapter.stopEditingProfiles();
517
518         profileListContainer.startAnimation(animation);
519         profileListHeadArrow.setRotation(0f);
520         profileListHeadArrow
521                 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
522         profileListHeadMore.setVisibility(View.GONE);
523     }
524     public void onProfileRowClicked(View v) {
525         Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
526     }
527     public void enableProfileModifications() {
528         profileModificationEnabled = true;
529         ViewGroup profileList = findViewById(R.id.nav_profile_list);
530         for (int i = 0; i < profileList.getChildCount(); i++) {
531             View aRow = profileList.getChildAt(i);
532             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
533             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
534         }
535         // FIXME enable rearranging
536
537     }
538     public void disableProfileModifications() {
539         profileModificationEnabled = false;
540         ViewGroup profileList = findViewById(R.id.nav_profile_list);
541         for (int i = 0; i < profileList.getChildCount(); i++) {
542             View aRow = profileList.getChildAt(i);
543             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
544             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
545         }
546         // FIXME disable rearranging
547
548     }
549
550     public class SectionsPagerAdapter extends FragmentPagerAdapter {
551
552         public SectionsPagerAdapter(FragmentManager fm) {
553             super(fm);
554         }
555
556         @Override
557         public Fragment getItem(int position) {
558             Log.d("main", String.format("Switching to fragment %d", position));
559             switch (position) {
560                 case 0:
561                     return new AccountSummaryFragment();
562                 case 1:
563                     return new TransactionListFragment();
564                 default:
565                     throw new IllegalStateException(
566                             String.format("Unexpected fragment index: " + "%d", position));
567             }
568         }
569
570         @Override
571         public int getCount() {
572             return 2;
573         }
574     }
575
576 }