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