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