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