]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
toCamelCase
[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.getOption(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 fabNewTransactionClicked(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 navExitClicked(View view) {
225         Log.w("app", "exiting");
226         finish();
227     }
228
229     public void navSettingsClicked(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         TransactionListFragment.accountFilter.set(null);
261 //        FragmentTransaction ft = fragmentManager.beginTransaction();
262 //        accountSummaryFragment = new AccountSummaryFragment();
263 //        ft.replace(R.id.root_frame, accountSummaryFragment);
264 //        ft.commit();
265 //        currentFragment = accountSummaryFragment;
266     }
267     public void onLatestTransactionsClicked(View view) {
268         drawer.closeDrawers();
269
270         showTransactionsFragment(null);
271     }
272     private void resetFragmentBackStack() {
273 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
274     }
275     private void showTransactionsFragment(LedgerAccount account) {
276         if (account != null) TransactionListFragment.accountFilter.set(account.getName());
277         mViewPager.setCurrentItem(1, true);
278 //        FragmentTransaction ft = fragmentManager.beginTransaction();
279 //        if (transactionListFragment == null) {
280 //            Log.d("flow", "MainActivity creating TransactionListFragment");
281 //            transactionListFragment = new TransactionListFragment();
282 //        }
283 //        Bundle bundle = new Bundle();
284 //        if (account != null) {
285 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
286 //                    account.getName());
287 //        }
288 //        transactionListFragment.setArguments(bundle);
289 //        ft.replace(R.id.root_frame, transactionListFragment);
290 //        if (account != null)
291 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
292 //        ft.commit();
293 //
294 //        currentFragment = transactionListFragment;
295     }
296     public void showAccountTransactions(LedgerAccount account) {
297         showTransactionsFragment(account);
298     }
299     @Override
300     public void onBackPressed() {
301         DrawerLayout drawer = findViewById(R.id.drawer_layout);
302         if (drawer.isDrawerOpen(GravityCompat.START)) {
303             drawer.closeDrawer(GravityCompat.START);
304         }
305         else {
306             Log.d("fragments",
307                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
308
309             super.onBackPressed();
310         }
311     }
312     public void updateLastUpdateTextFromDB() {
313         {
314             long last_update = Data.profile.get().getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
315
316             Log.d("transactions", String.format("Last update = %d", last_update));
317             if (last_update == 0) {
318                 Data.lastUpdateDate.set(null);
319             }
320             else {
321                 Data.lastUpdateDate.set(new Date(last_update));
322             }
323         }
324     }
325     public void scheduleTransactionListRetrieval() {
326         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
327
328         retrieveTransactionsTask.execute();
329         bTransactionListCancelDownload.setEnabled(true);
330     }
331     public void onStopTransactionRefreshClick(View view) {
332         Log.d("interactive", "Cancelling transactions refresh");
333         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
334         bTransactionListCancelDownload.setEnabled(false);
335     }
336     public void onRetrieveDone(boolean success) {
337         progressLayout.setVisibility(View.GONE);
338         updateLastUpdateTextFromDB();
339
340         new RefreshDescriptionsTask().execute();
341     }
342     public void onRetrieveStart() {
343         progressBar.setIndeterminate(true);
344         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
345         else progressBar.setProgress(0);
346         progressLayout.setVisibility(View.VISIBLE);
347     }
348     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
349         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
350             (progress.getTotal() == 0))
351         {
352             progressBar.setIndeterminate(true);
353         }
354         else {
355             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
356                 progressBar.setMin(0);
357             }
358             progressBar.setMax(progress.getTotal());
359             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
360                 progressBar.setProgress(progress.getProgress(), true);
361             }
362             else progressBar.setProgress(progress.getProgress());
363             progressBar.setIndeterminate(false);
364         }
365     }
366     public void navProfilesClicked(View view) {
367         drawer.closeDrawers();
368         Intent intent = new Intent(this, ProfileListActivity.class);
369         startActivity(intent);
370     }
371     public class SectionsPagerAdapter extends FragmentPagerAdapter {
372
373         public SectionsPagerAdapter(FragmentManager fm) {
374             super(fm);
375         }
376
377         @Override
378         public Fragment getItem(int position) {
379             Log.d("main", String.format("Switching to gragment %d", position));
380             switch (position) {
381                 case 0:
382                     return new AccountSummaryFragment();
383                 case 1:
384                     return new TransactionListFragment();
385                 default:
386                     throw new IllegalStateException(
387                             String.format("Unexpected fragment index: " + "%d", position));
388             }
389         }
390
391         @Override
392         public int getCount() {
393             return 2;
394         }
395     }
396
397 }