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