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