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