]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
migrate to AndroidX
[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.Build;
25 import android.os.Bundle;
26 import com.google.android.material.floatingactionbutton.FloatingActionButton;
27 import androidx.fragment.app.Fragment;
28 import androidx.fragment.app.FragmentManager;
29 import androidx.fragment.app.FragmentPagerAdapter;
30 import androidx.core.view.GravityCompat;
31 import androidx.viewpager.widget.ViewPager;
32 import androidx.drawerlayout.widget.DrawerLayout;
33 import androidx.appcompat.app.ActionBarDrawerToggle;
34 import androidx.appcompat.widget.Toolbar;
35 import android.util.Log;
36 import android.view.View;
37 import android.widget.LinearLayout;
38 import android.widget.ProgressBar;
39 import android.widget.TextView;
40 import android.widget.Toast;
41
42 import net.ktnx.mobileledger.R;
43 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
44 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
45 import net.ktnx.mobileledger.model.Data;
46 import net.ktnx.mobileledger.model.LedgerAccount;
47 import net.ktnx.mobileledger.model.MobileLedgerProfile;
48 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
49 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
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
57 public class MainActivity extends CrashReportingActivity {
58     DrawerLayout drawer;
59     private FragmentManager fragmentManager;
60     private TextView tvLastUpdate;
61     private RetrieveTransactionsTask retrieveTransactionsTask;
62     private View bTransactionListCancelDownload;
63     private ProgressBar progressBar;
64     private LinearLayout progressLayout;
65     private SectionsPagerAdapter mSectionsPagerAdapter;
66     private ViewPager mViewPager;
67     private FloatingActionButton fab;
68
69     @Override
70     protected void onStart() {
71         super.onStart();
72
73         Data.lastUpdateDate.set(null);
74         updateLastUpdateTextFromDB();
75         Date lastUpdate = Data.lastUpdateDate.get();
76
77         long now = new Date().getTime();
78         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
79             if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
80             else Log.d("db",
81                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
82                             lastUpdate.getTime() / 1000f, now / 1000f));
83
84             scheduleTransactionListRetrieval();
85         }
86     }
87     @Override
88     protected void onCreate(Bundle savedInstanceState) {
89         super.onCreate(savedInstanceState);
90
91         setContentView(R.layout.activity_main);
92         Toolbar toolbar = findViewById(R.id.toolbar);
93         setSupportActionBar(toolbar);
94         fab = findViewById(R.id.btn_add_transaction);
95
96         Data.profile.addObserver((o, arg) -> {
97             MobileLedgerProfile profile = Data.profile.get();
98             runOnUiThread(() -> {
99                 if (profile == null) setTitle(R.string.app_name);
100                 else setTitle(profile.getName());
101                 updateLastUpdateTextFromDB();
102                 if (profile.isPostingPermitted()) {
103                     toolbar.setSubtitle(null);
104                     fab.show();
105                 }
106                 else {
107                     toolbar.setSubtitle(R.string.profile_subitlte_read_only);
108                     fab.hide();
109                 }
110
111                 int newProfileTheme = profile.getThemeId();
112                 if (newProfileTheme != Colors.profileThemeId) {
113                     Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
114                             newProfileTheme));
115                     profileThemeChanged();
116                     Colors.profileThemeId = newProfileTheme;
117                 }
118             });
119         });
120
121         drawer = findViewById(R.id.drawer_layout);
122         ActionBarDrawerToggle toggle =
123                 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
124                         R.string.navigation_drawer_close);
125         drawer.addDrawerListener(toggle);
126         toggle.syncState();
127
128         TextView ver = drawer.findViewById(R.id.drawer_version_text);
129
130         try {
131             PackageInfo pi =
132                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
133             ver.setText(pi.versionName);
134         }
135         catch (Exception e) {
136             e.printStackTrace();
137         }
138
139         tvLastUpdate = findViewById(R.id.transactions_last_update);
140
141         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
142         progressBar = findViewById(R.id.transaction_list_progress_bar);
143         if (progressBar == null)
144             throw new RuntimeException("Can't get hold on the transaction value progress bar");
145         progressLayout = findViewById(R.id.transaction_progress_layout);
146         if (progressLayout == null) throw new RuntimeException(
147                 "Can't get hold on the transaction value progress bar layout");
148
149         fragmentManager = getSupportFragmentManager();
150         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
151
152         markDrawerItemCurrent(R.id.nav_account_summary);
153
154         mViewPager = findViewById(R.id.root_frame);
155         mViewPager.setAdapter(mSectionsPagerAdapter);
156         mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
157             @Override
158             public void onPageSelected(int position) {
159                 switch (position) {
160                     case 0:
161                         markDrawerItemCurrent(R.id.nav_account_summary);
162                         break;
163                     case 1:
164                         markDrawerItemCurrent(R.id.nav_latest_transactions);
165                         break;
166                     default:
167                         Log.e("MainActivity", String.format("Unexpected page index %d", position));
168                 }
169
170                 super.onPageSelected(position);
171             }
172         });
173
174         Data.lastUpdateDate.addObserver((o, arg) -> {
175             Log.d("main", "lastUpdateDate changed");
176             runOnUiThread(() -> {
177                 Date date = Data.lastUpdateDate.get();
178                 if (date == null) {
179                     tvLastUpdate.setText(R.string.transaction_last_update_never);
180                 }
181                 else {
182                     final String text = DateFormat.getDateTimeInstance().format(date);
183                     tvLastUpdate.setText(text);
184                     Log.d("despair", String.format("Date formatted: %s", text));
185                 }
186             });
187         });
188
189         findViewById(R.id.btn_no_profiles_add).setOnClickListener(v -> startAddProfileActivity());
190
191         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
192     }
193     private void profileThemeChanged() {
194         setupProfileColors();
195
196         // restart activity to reflect theme change
197         finish();
198         Intent intent = new Intent(this, this.getClass());
199         startActivity(intent);
200     }
201     @Override
202     protected void onResume() {
203         super.onResume();
204         setupProfile();
205     }
206     private void startAddProfileActivity() {
207         Intent intent = new Intent(this, ProfileListActivity.class);
208         Bundle args = new Bundle();
209         args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
210         args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, ProfileListActivity.PROFILE_INDEX_NONE);
211         intent.putExtras(args);
212         startActivity(intent, args);
213     }
214     private void setupProfile() {
215         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
216         MobileLedgerProfile profile;
217
218         profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
219
220         if (Data.profiles.getList().isEmpty()) {
221             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
222             findViewById(R.id.pager_layout).setVisibility(View.GONE);
223             return;
224         }
225
226         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
227         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
228
229         if (profile == null) profile = Data.profiles.get(0);
230
231         if (profile == null) throw new AssertionError("profile must have a value");
232
233         Data.setCurrentProfile(profile);
234     }
235     public void fabNewTransactionClicked(View view) {
236         Intent intent = new Intent(this, NewTransactionActivity.class);
237         startActivity(intent);
238         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
239     }
240     public void navSettingsClicked(View view) {
241         Intent intent = new Intent(this, SettingsActivity.class);
242         startActivity(intent);
243         drawer.closeDrawers();
244     }
245     public void markDrawerItemCurrent(int id) {
246         TextView item = drawer.findViewById(id);
247         item.setBackgroundColor(Colors.tableRowDarkBG);
248
249         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
250         for (int i = 0; i < actions.getChildCount(); i++) {
251             View view = actions.getChildAt(i);
252             if (view.getId() != id) {
253                 view.setBackgroundColor(Color.TRANSPARENT);
254             }
255         }
256     }
257     public void onAccountSummaryClicked(View view) {
258         drawer.closeDrawers();
259
260         showAccountSummaryFragment();
261     }
262     private void showAccountSummaryFragment() {
263         mViewPager.setCurrentItem(0, true);
264         TransactionListFragment.accountFilter.set(null);
265 //        FragmentTransaction ft = fragmentManager.beginTransaction();
266 //        accountSummaryFragment = new AccountSummaryFragment();
267 //        ft.replace(R.id.root_frame, accountSummaryFragment);
268 //        ft.commit();
269 //        currentFragment = accountSummaryFragment;
270     }
271     public void onLatestTransactionsClicked(View view) {
272         drawer.closeDrawers();
273
274         showTransactionsFragment(null);
275     }
276     private void resetFragmentBackStack() {
277 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
278     }
279     private void showTransactionsFragment(LedgerAccount account) {
280         if (account != null) TransactionListFragment.accountFilter.set(account.getName());
281         mViewPager.setCurrentItem(1, true);
282 //        FragmentTransaction ft = fragmentManager.beginTransaction();
283 //        if (transactionListFragment == null) {
284 //            Log.d("flow", "MainActivity creating TransactionListFragment");
285 //            transactionListFragment = new TransactionListFragment();
286 //        }
287 //        Bundle bundle = new Bundle();
288 //        if (account != null) {
289 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
290 //                    account.getName());
291 //        }
292 //        transactionListFragment.setArguments(bundle);
293 //        ft.replace(R.id.root_frame, transactionListFragment);
294 //        if (account != null)
295 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
296 //        ft.commit();
297 //
298 //        currentFragment = transactionListFragment;
299     }
300     public void showAccountTransactions(LedgerAccount account) {
301         showTransactionsFragment(account);
302     }
303     @Override
304     public void onBackPressed() {
305         DrawerLayout drawer = findViewById(R.id.drawer_layout);
306         if (drawer.isDrawerOpen(GravityCompat.START)) {
307             drawer.closeDrawer(GravityCompat.START);
308         }
309         else {
310             Log.d("fragments",
311                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
312
313             super.onBackPressed();
314         }
315     }
316     public void updateLastUpdateTextFromDB() {
317         {
318             final MobileLedgerProfile profile = Data.profile.get();
319             long last_update =
320                     (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
321
322             Log.d("transactions", String.format("Last update = %d", last_update));
323             if (last_update == 0) {
324                 Data.lastUpdateDate.set(null);
325             }
326             else {
327                 Data.lastUpdateDate.set(new Date(last_update));
328             }
329         }
330     }
331     public void scheduleTransactionListRetrieval() {
332         if (Data.profile.get() == null) return;
333
334         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
335
336         retrieveTransactionsTask.execute();
337         bTransactionListCancelDownload.setEnabled(true);
338     }
339     public void onStopTransactionRefreshClick(View view) {
340         Log.d("interactive", "Cancelling transactions refresh");
341         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
342         bTransactionListCancelDownload.setEnabled(false);
343     }
344     public void onRetrieveDone(String error) {
345         progressLayout.setVisibility(View.GONE);
346
347         if (error == null) {
348             updateLastUpdateTextFromDB();
349
350             new RefreshDescriptionsTask().execute();
351         }
352         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
353     }
354     public void onRetrieveStart() {
355         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
356         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
357         progressBar.setIndeterminate(true);
358         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
359         else progressBar.setProgress(0);
360         progressLayout.setVisibility(View.VISIBLE);
361     }
362     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
363         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
364             (progress.getTotal() == 0))
365         {
366             progressBar.setIndeterminate(true);
367         }
368         else {
369             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
370                 progressBar.setMin(0);
371             }
372             progressBar.setMax(progress.getTotal());
373             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
374                 progressBar.setProgress(progress.getProgress(), true);
375             }
376             else progressBar.setProgress(progress.getProgress());
377             progressBar.setIndeterminate(false);
378         }
379     }
380     public void navProfilesClicked(View view) {
381         drawer.closeDrawers();
382         Intent intent = new Intent(this, ProfileListActivity.class);
383         startActivity(intent);
384     }
385     public void fabShouldShow() {
386         MobileLedgerProfile profile = Data.profile.get();
387         if ((profile != null) && profile.isPostingPermitted()) fab.show();
388     }
389
390     public class SectionsPagerAdapter extends FragmentPagerAdapter {
391
392         public SectionsPagerAdapter(FragmentManager fm) {
393             super(fm);
394         }
395
396         @Override
397         public Fragment getItem(int position) {
398             Log.d("main", String.format("Switching to fragment %d", position));
399             switch (position) {
400                 case 0:
401                     return new AccountSummaryFragment();
402                 case 1:
403                     return new TransactionListFragment();
404                 default:
405                     throw new IllegalStateException(
406                             String.format("Unexpected fragment index: " + "%d", position));
407             }
408         }
409
410         @Override
411         public int getCount() {
412             return 2;
413         }
414     }
415 }