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