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