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