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