]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
update description list after transaction retrieval
[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.SharedPreferences;
22 import android.content.pm.PackageInfo;
23 import android.os.Build;
24 import android.os.Bundle;
25 import android.support.annotation.ColorInt;
26 import android.support.v4.app.Fragment;
27 import android.support.v4.app.FragmentManager;
28 import android.support.v4.app.FragmentPagerAdapter;
29 import android.support.v4.view.GravityCompat;
30 import android.support.v4.view.ViewPager;
31 import android.support.v4.widget.DrawerLayout;
32 import android.support.v7.app.ActionBarDrawerToggle;
33 import android.support.v7.app.AppCompatActivity;
34 import android.support.v7.widget.Toolbar;
35 import android.util.Log;
36 import android.view.ContextMenu;
37 import android.view.MenuItem;
38 import android.view.View;
39 import android.widget.LinearLayout;
40 import android.widget.ProgressBar;
41 import android.widget.TextView;
42
43 import net.ktnx.mobileledger.R;
44 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
45 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
46 import net.ktnx.mobileledger.model.Data;
47 import net.ktnx.mobileledger.model.LedgerAccount;
48 import net.ktnx.mobileledger.model.MobileLedgerProfile;
49 import net.ktnx.mobileledger.ui.MobileLedgerListFragment;
50 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
51 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
52 import net.ktnx.mobileledger.utils.MLDB;
53
54 import java.lang.ref.WeakReference;
55 import java.time.ZoneId;
56 import java.time.format.DateTimeFormatter;
57 import java.util.Date;
58 import java.util.Observable;
59 import java.util.Observer;
60
61 public class MainActivity extends AppCompatActivity {
62     public MobileLedgerListFragment currentFragment = null;
63     DrawerLayout drawer;
64     private AccountSummaryFragment accountSummaryFragment;
65     private TransactionListFragment transactionListFragment;
66     private FragmentManager fragmentManager;
67     private TextView tvLastUpdate;
68     private RetrieveTransactionsTask retrieveTransactionsTask;
69     private View bTransactionListCancelDownload;
70     private ProgressBar progressBar;
71     private LinearLayout progressLayout;
72     private SectionsPagerAdapter mSectionsPagerAdapter;
73     private ViewPager mViewPager;
74
75     @Override
76     protected void onStart() {
77         super.onStart();
78
79         Data.lastUpdateDate.set(null);
80         updateLastUpdateTextFromDB();
81         Date lastUpdate = Data.lastUpdateDate.get();
82
83         long now = new Date().getTime();
84         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
85             if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
86             else Log.d("db",
87                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
88                             lastUpdate.getTime() / 1000f, now / 1000f));
89
90             scheduleTransactionListRetrieval();
91         }
92     }
93     @Override
94     protected void onCreate(Bundle savedInstanceState) {
95         super.onCreate(savedInstanceState);
96         setContentView(R.layout.activity_main);
97         Toolbar toolbar = findViewById(R.id.toolbar);
98         setSupportActionBar(toolbar);
99
100         Data.profile.addObserver(new Observer() {
101             @Override
102             public void update(Observable o, Object arg) {
103                 MobileLedgerProfile profile = Data.profile.get();
104                 runOnUiThread(() -> {
105                     if (profile == null) toolbar.setSubtitle("");
106                     else toolbar.setSubtitle(profile.getName());
107                 });
108             }
109         });
110
111         setupProfile();
112
113         drawer = findViewById(R.id.drawer_layout);
114         ActionBarDrawerToggle toggle =
115                 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
116                         R.string.navigation_drawer_close);
117         drawer.addDrawerListener(toggle);
118         toggle.syncState();
119
120         android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
121
122         try {
123             PackageInfo pi =
124                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
125             ver.setText(pi.versionName);
126         }
127         catch (Exception e) {
128             e.printStackTrace();
129         }
130
131         tvLastUpdate = findViewById(R.id.transactions_last_update);
132
133         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
134         progressBar = findViewById(R.id.transaction_list_progress_bar);
135         if (progressBar == null)
136             throw new RuntimeException("Can't get hold on the transaction value progress bar");
137         progressLayout = findViewById(R.id.transaction_progress_layout);
138         if (progressLayout == null) throw new RuntimeException(
139                 "Can't get hold on the transaction value progress bar layout");
140
141         fragmentManager = getSupportFragmentManager();
142         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
143
144         mViewPager = findViewById(R.id.root_frame);
145         mViewPager.setAdapter(mSectionsPagerAdapter);
146         mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
147             @Override
148             public void onPageSelected(int position) {
149                 switch (position) {
150                     case 0:
151                         markDrawerItemCurrent(R.id.nav_account_summary);
152                         break;
153                     case 1:
154                         markDrawerItemCurrent(R.id.nav_latest_transactions);
155                         break;
156                     default:
157                         Log.e("MainActivity", String.format("Unexpected page index %d", position));
158                 }
159
160                 super.onPageSelected(position);
161             }
162         });
163
164         Data.lastUpdateDate.addObserver(new Observer() {
165             @Override
166             public void update(Observable o, Object arg) {
167                 Log.d("main", "lastUpdateDate changed");
168                 runOnUiThread(() -> {
169                     Date date = Data.lastUpdateDate.get();
170                     if (date == null) {
171                         tvLastUpdate.setText(R.string.transaction_last_update_never);
172                     }
173                     else {
174                         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
175                             tvLastUpdate.setText(date.toInstant().atZone(ZoneId.systemDefault())
176                                     .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
177                         }
178                         else {
179                             tvLastUpdate.setText(date.toLocaleString());
180                         }
181                     }
182                 });
183             }
184         });
185     }
186     private void setupProfile() {
187         Data.profiles.setList(MobileLedgerProfile.loadAllFromDB());
188         MobileLedgerProfile profile = null;
189
190         String profileUUID = MLDB.get_option_value(MLDB.OPT_PROFILE_UUID, null);
191         if (profileUUID == null) {
192             if (Data.profiles.isEmpty()) {
193                 Data.profiles.setList(MobileLedgerProfile.createInitialProfileList());
194                 profile = Data.profiles.get(0);
195
196                 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
197                 Log.d("profiles", "Migrating from preferences to profiles");
198                 // migration to multiple profiles
199                 if (profile.getUrl().isEmpty()) {
200                     // no legacy config
201                     Intent intent = new Intent(this, ProfileListActivity.class);
202                     startActivity(intent);
203                 }
204                 profile.setUrl(backend.getString("backend_url", ""));
205                 profile.setAuthEnabled(backend.getBoolean("backend_use_http_auth", false));
206                 profile.setAuthUserName(backend.getString("backend_auth_user", null));
207                 profile.setAuthPassword(backend.getString("backend_auth_password", null));
208                 profile.storeInDB();
209                 SharedPreferences.Editor editor = backend.edit();
210                 editor.clear();
211                 editor.apply();
212             }
213         }
214         else {
215             profile = MobileLedgerProfile.loadUUIDFromDB(profileUUID);
216         }
217
218         if (profile == null) profile = Data.profiles.get(0);
219
220         if (profile == null) throw new AssertionError("profile must have a value");
221
222         Data.profile.set(profile);
223         MLDB.set_option_value(MLDB.OPT_PROFILE_UUID, profile.getUuid());
224
225         if (profile.getUrl().isEmpty()) {
226             Intent intent = new Intent(this, ProfileListActivity.class);
227             Bundle args = new Bundle();
228             args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
229             args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, 0);
230             intent.putExtras(args);
231             startActivity(intent, args);
232         }
233     }
234     public void fab_new_transaction_clicked(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
240     public void nav_exit_clicked(View view) {
241         Log.w("app", "exiting");
242         finish();
243     }
244
245     public void nav_settings_clicked(View view) {
246         Intent intent = new Intent(this, SettingsActivity.class);
247         startActivity(intent);
248     }
249     public void markDrawerItemCurrent(int id) {
250         TextView item = drawer.findViewById(id);
251         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
252             item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
253         }
254         else {
255             item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
256         }
257
258         setTitle(item.getText());
259
260         @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
261
262         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
263         for (int i = 0; i < actions.getChildCount(); i++) {
264             View view = actions.getChildAt(i);
265             if (view.getId() != id) {
266                 view.setBackgroundColor(transparent);
267             }
268         }
269     }
270     public void onOptionsMenuClicked(MenuItem menuItem) {
271         ContextMenu.ContextMenuInfo info = menuItem.getMenuInfo();
272         switch (menuItem.getItemId()) {
273             case R.id.menu_acc_summary_cancel_selection:
274                 if (accountSummaryFragment != null)
275                     accountSummaryFragment.onCancelAccSelection(menuItem);
276                 break;
277             case R.id.menu_acc_summary_confirm_selection:
278                 if (accountSummaryFragment != null)
279                     accountSummaryFragment.onConfirmAccSelection(menuItem);
280                 break;
281             case R.id.menu_acc_summary_only_starred:
282                 if (accountSummaryFragment != null)
283                     accountSummaryFragment.onShowOnlyStarredClicked(menuItem);
284                 break;
285             case R.id.menu_transaction_list_filter:
286                 if (transactionListFragment != null)
287                     transactionListFragment.onShowFilterClick(menuItem);
288                 break;
289             default:
290                 Log.e("menu", String.format("Menu item %d not handled", menuItem.getItemId()));
291         }
292     }
293     public void onViewClicked(View view) {
294         switch (view.getId()) {
295             case R.id.clearAccountNameFilter:
296                 if (transactionListFragment != null)
297                     transactionListFragment.onClearAccountNameClick(view);
298                 break;
299             default:
300                 Log.e("click", String.format("View %d click not handled", view.getId()));
301         }
302     }
303     public void onAccountSummaryClicked(View view) {
304         drawer.closeDrawers();
305
306         showAccountSummaryFragment();
307     }
308     private void showAccountSummaryFragment() {
309         mViewPager.setCurrentItem(0, true);
310 //        FragmentTransaction ft = fragmentManager.beginTransaction();
311 //        accountSummaryFragment = new AccountSummaryFragment();
312 //        ft.replace(R.id.root_frame, accountSummaryFragment);
313 //        ft.commit();
314 //        currentFragment = accountSummaryFragment;
315     }
316     public void onLatestTransactionsClicked(View view) {
317         drawer.closeDrawers();
318
319         showTransactionsFragment(null);
320     }
321     private void resetFragmentBackStack() {
322 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
323     }
324     private void showTransactionsFragment(LedgerAccount account) {
325         mViewPager.setCurrentItem(1, true);
326 //        FragmentTransaction ft = fragmentManager.beginTransaction();
327 //        if (transactionListFragment == null) {
328 //            Log.d("flow", "MainActivity creating TransactionListFragment");
329 //            transactionListFragment = new TransactionListFragment();
330 //        }
331 //        Bundle bundle = new Bundle();
332 //        if (account != null) {
333 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
334 //                    account.getName());
335 //        }
336 //        transactionListFragment.setArguments(bundle);
337 //        ft.replace(R.id.root_frame, transactionListFragment);
338 //        if (account != null)
339 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
340 //        ft.commit();
341 //
342 //        currentFragment = transactionListFragment;
343     }
344     public void showAccountTransactions(LedgerAccount account) {
345         showTransactionsFragment(account);
346     }
347     @Override
348     public void onBackPressed() {
349         DrawerLayout drawer = findViewById(R.id.drawer_layout);
350         if (drawer.isDrawerOpen(GravityCompat.START)) {
351             drawer.closeDrawer(GravityCompat.START);
352         }
353         else {
354             Log.d("fragments",
355                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
356
357             super.onBackPressed();
358         }
359     }
360     public void updateLastUpdateTextFromDB() {
361         {
362             long last_update = Data.profile.get().get_option_value(MLDB.OPT_LAST_SCRAPE, 0L);
363
364             Log.d("transactions", String.format("Last update = %d", last_update));
365             if (last_update == 0) {
366                 Data.lastUpdateDate.set(null);
367             }
368             else {
369                 Data.lastUpdateDate.set(new Date(last_update));
370             }
371         }
372     }
373     public void scheduleTransactionListRetrieval() {
374         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
375
376         retrieveTransactionsTask.execute();
377         bTransactionListCancelDownload.setEnabled(true);
378     }
379     public void onStopTransactionRefreshClick(View view) {
380         Log.d("interactive", "Cancelling transactions refresh");
381         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
382         bTransactionListCancelDownload.setEnabled(false);
383     }
384     public void onRetrieveDone(boolean success) {
385         progressLayout.setVisibility(View.GONE);
386         updateLastUpdateTextFromDB();
387
388         new RefreshDescriptionsTask().execute();
389     }
390     public void onRetrieveStart() {
391         progressBar.setIndeterminate(true);
392         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
393         else progressBar.setProgress(0);
394         progressLayout.setVisibility(View.VISIBLE);
395     }
396     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
397         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
398             (progress.getTotal() == 0))
399         {
400             progressBar.setIndeterminate(true);
401         }
402         else {
403             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
404                 progressBar.setMin(0);
405             }
406             progressBar.setMax(progress.getTotal());
407             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
408                 progressBar.setProgress(progress.getProgress(), true);
409             }
410             else progressBar.setProgress(progress.getProgress());
411             progressBar.setIndeterminate(false);
412         }
413     }
414     public void nav_profiles_clicked(View view) {
415         drawer.closeDrawers();
416         Intent intent = new Intent(this, ProfileListActivity.class);
417         startActivity(intent);
418     }
419     public class SectionsPagerAdapter extends FragmentPagerAdapter {
420
421         public SectionsPagerAdapter(FragmentManager fm) {
422             super(fm);
423         }
424
425         @Override
426         public Fragment getItem(int position) {
427             Log.d("main", String.format("Switching to gragment %d", position));
428             switch (position) {
429                 case 0:
430                     return new AccountSummaryFragment();
431                 case 1:
432                     return new TransactionListFragment();
433                 default:
434                     throw new IllegalStateException(
435                             String.format("Unexpected fragment index: " + "%d", position));
436             }
437         }
438
439         @Override
440         public int getCount() {
441             return 2;
442         }
443     }
444
445 }