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