]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
use Colors.* for run-time color control
[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 MoLe.
4  * MoLe 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  * MoLe 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 MoLe. 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.pm.PackageInfo;
22 import android.content.res.ColorStateList;
23 import android.graphics.Color;
24 import android.os.Build;
25 import android.os.Bundle;
26 import android.support.design.widget.FloatingActionButton;
27 import android.support.v4.app.Fragment;
28 import android.support.v4.app.FragmentManager;
29 import android.support.v4.app.FragmentPagerAdapter;
30 import android.support.v4.view.GravityCompat;
31 import android.support.v4.view.ViewPager;
32 import android.support.v4.widget.DrawerLayout;
33 import android.support.v7.app.ActionBarDrawerToggle;
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.Colors;
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 CrashReportingActivity {
58     DrawerLayout drawer;
59     private FragmentManager fragmentManager;
60     private TextView tvLastUpdate;
61     private RetrieveTransactionsTask retrieveTransactionsTask;
62     private View bTransactionListCancelDownload;
63     private ProgressBar progressBar;
64     private LinearLayout progressLayout;
65     private SectionsPagerAdapter mSectionsPagerAdapter;
66     private ViewPager mViewPager;
67     private FloatingActionButton fab;
68
69     @Override
70     protected void onStart() {
71         super.onStart();
72
73         Data.lastUpdateDate.set(null);
74         updateLastUpdateTextFromDB();
75         Date lastUpdate = Data.lastUpdateDate.get();
76
77         long now = new Date().getTime();
78         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
79             if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
80             else Log.d("db",
81                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
82                             lastUpdate.getTime() / 1000f, now / 1000f));
83
84             scheduleTransactionListRetrieval();
85         }
86     }
87     @Override
88     protected void onCreate(Bundle savedInstanceState) {
89         super.onCreate(savedInstanceState);
90         setContentView(R.layout.activity_main);
91         Toolbar toolbar = findViewById(R.id.toolbar);
92         setSupportActionBar(toolbar);
93         fab = findViewById(R.id.btn_add_transaction);
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                 updateLastUpdateTextFromDB();
101                 if (profile.isPostingPermitted()) {
102                     toolbar.setSubtitle(null);
103                     fab.show();
104                 }
105                 else {
106                     toolbar.setSubtitle(R.string.profile_subitlte_read_only);
107                     fab.hide();
108                 }
109             });
110         });
111
112         drawer = findViewById(R.id.drawer_layout);
113         ActionBarDrawerToggle toggle =
114                 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
115                         R.string.navigation_drawer_close);
116         drawer.addDrawerListener(toggle);
117         toggle.syncState();
118
119         TextView ver = drawer.findViewById(R.id.drawer_version_text);
120
121         try {
122             PackageInfo pi =
123                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
124             ver.setText(pi.versionName);
125         }
126         catch (Exception e) {
127             e.printStackTrace();
128         }
129
130         tvLastUpdate = findViewById(R.id.transactions_last_update);
131
132         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
133         progressBar = findViewById(R.id.transaction_list_progress_bar);
134         if (progressBar == null)
135             throw new RuntimeException("Can't get hold on the transaction value progress bar");
136         progressLayout = findViewById(R.id.transaction_progress_layout);
137         if (progressLayout == null) throw new RuntimeException(
138                 "Can't get hold on the transaction value progress bar layout");
139
140         fragmentManager = getSupportFragmentManager();
141         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
142
143         markDrawerItemCurrent(R.id.nav_account_summary);
144
145         mViewPager = findViewById(R.id.root_frame);
146         mViewPager.setAdapter(mSectionsPagerAdapter);
147         mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
148             @Override
149             public void onPageSelected(int position) {
150                 switch (position) {
151                     case 0:
152                         markDrawerItemCurrent(R.id.nav_account_summary);
153                         break;
154                     case 1:
155                         markDrawerItemCurrent(R.id.nav_latest_transactions);
156                         break;
157                     default:
158                         Log.e("MainActivity", String.format("Unexpected page index %d", position));
159                 }
160
161                 super.onPageSelected(position);
162             }
163         });
164
165         Data.lastUpdateDate.addObserver((o, arg) -> {
166             Log.d("main", "lastUpdateDate changed");
167             runOnUiThread(() -> {
168                 Date date = Data.lastUpdateDate.get();
169                 if (date == null) {
170                     tvLastUpdate.setText(R.string.transaction_last_update_never);
171                 }
172                 else {
173                     final String text = DateFormat.getDateTimeInstance().format(date);
174                     tvLastUpdate.setText(text);
175                     Log.d("despair", String.format("Date formatted: %s", text));
176                 }
177             });
178         });
179
180         findViewById(R.id.btn_no_profiles_add).setOnClickListener(v -> startAddProfileActivity());
181
182         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
183     }
184     @Override
185     protected void onResume() {
186         super.onResume();
187         setupProfile();
188     }
189     private void startAddProfileActivity() {
190         Intent intent = new Intent(this, ProfileListActivity.class);
191         Bundle args = new Bundle();
192         args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
193         args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, ProfileListActivity.PROFILE_INDEX_NONE);
194         intent.putExtras(args);
195         startActivity(intent, args);
196     }
197     private void setupProfile() {
198         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
199         MobileLedgerProfile profile;
200
201         profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
202
203         if (Data.profiles.getList().isEmpty()) {
204             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
205             findViewById(R.id.pager_layout).setVisibility(View.GONE);
206             return;
207         }
208
209         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
210         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
211
212         if (profile == null) profile = Data.profiles.get(0);
213
214         if (profile == null) throw new AssertionError("profile must have a value");
215
216         Data.setCurrentProfile(profile);
217     }
218     public void fabNewTransactionClicked(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     public void navSettingsClicked(View view) {
224         Intent intent = new Intent(this, SettingsActivity.class);
225         startActivity(intent);
226         drawer.closeDrawers();
227     }
228     public void markDrawerItemCurrent(int id) {
229         TextView item = drawer.findViewById(id);
230         item.setBackgroundColor(Colors.tableRowDarkBG);
231
232         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
233         for (int i = 0; i < actions.getChildCount(); i++) {
234             View view = actions.getChildAt(i);
235             if (view.getId() != id) {
236                 view.setBackgroundColor(Color.TRANSPARENT);
237             }
238         }
239     }
240     public void onAccountSummaryClicked(View view) {
241         drawer.closeDrawers();
242
243         showAccountSummaryFragment();
244     }
245     private void showAccountSummaryFragment() {
246         mViewPager.setCurrentItem(0, true);
247         TransactionListFragment.accountFilter.set(null);
248 //        FragmentTransaction ft = fragmentManager.beginTransaction();
249 //        accountSummaryFragment = new AccountSummaryFragment();
250 //        ft.replace(R.id.root_frame, accountSummaryFragment);
251 //        ft.commit();
252 //        currentFragment = accountSummaryFragment;
253     }
254     public void onLatestTransactionsClicked(View view) {
255         drawer.closeDrawers();
256
257         showTransactionsFragment(null);
258     }
259     private void resetFragmentBackStack() {
260 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
261     }
262     private void showTransactionsFragment(LedgerAccount account) {
263         if (account != null) TransactionListFragment.accountFilter.set(account.getName());
264         mViewPager.setCurrentItem(1, true);
265 //        FragmentTransaction ft = fragmentManager.beginTransaction();
266 //        if (transactionListFragment == null) {
267 //            Log.d("flow", "MainActivity creating TransactionListFragment");
268 //            transactionListFragment = new TransactionListFragment();
269 //        }
270 //        Bundle bundle = new Bundle();
271 //        if (account != null) {
272 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
273 //                    account.getName());
274 //        }
275 //        transactionListFragment.setArguments(bundle);
276 //        ft.replace(R.id.root_frame, transactionListFragment);
277 //        if (account != null)
278 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
279 //        ft.commit();
280 //
281 //        currentFragment = transactionListFragment;
282     }
283     public void showAccountTransactions(LedgerAccount account) {
284         showTransactionsFragment(account);
285     }
286     @Override
287     public void onBackPressed() {
288         DrawerLayout drawer = findViewById(R.id.drawer_layout);
289         if (drawer.isDrawerOpen(GravityCompat.START)) {
290             drawer.closeDrawer(GravityCompat.START);
291         }
292         else {
293             Log.d("fragments",
294                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
295
296             super.onBackPressed();
297         }
298     }
299     public void updateLastUpdateTextFromDB() {
300         {
301             final MobileLedgerProfile profile = Data.profile.get();
302             long last_update =
303                     (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
304
305             Log.d("transactions", String.format("Last update = %d", last_update));
306             if (last_update == 0) {
307                 Data.lastUpdateDate.set(null);
308             }
309             else {
310                 Data.lastUpdateDate.set(new Date(last_update));
311             }
312         }
313     }
314     public void scheduleTransactionListRetrieval() {
315         if (Data.profile.get() == null) return;
316
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.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
339         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
340         progressBar.setIndeterminate(true);
341         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
342         else progressBar.setProgress(0);
343         progressLayout.setVisibility(View.VISIBLE);
344     }
345     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
346         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
347             (progress.getTotal() == 0))
348         {
349             progressBar.setIndeterminate(true);
350         }
351         else {
352             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
353                 progressBar.setMin(0);
354             }
355             progressBar.setMax(progress.getTotal());
356             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
357                 progressBar.setProgress(progress.getProgress(), true);
358             }
359             else progressBar.setProgress(progress.getProgress());
360             progressBar.setIndeterminate(false);
361         }
362     }
363     public void navProfilesClicked(View view) {
364         drawer.closeDrawers();
365         Intent intent = new Intent(this, ProfileListActivity.class);
366         startActivity(intent);
367     }
368     public class SectionsPagerAdapter extends FragmentPagerAdapter {
369
370         public SectionsPagerAdapter(FragmentManager fm) {
371             super(fm);
372         }
373
374         @Override
375         public Fragment getItem(int position) {
376             Log.d("main", String.format("Switching to fragment %d", position));
377             switch (position) {
378                 case 0:
379                     return new AccountSummaryFragment();
380                 case 1:
381                     return new TransactionListFragment();
382                 default:
383                     throw new IllegalStateException(
384                             String.format("Unexpected fragment index: " + "%d", position));
385             }
386         }
387
388         @Override
389         public int getCount() {
390             return 2;
391         }
392     }
393     public void fabShouldShow() {
394         MobileLedgerProfile profile = Data.profile.get();
395         if ((profile != null) && profile.isPostingPermitted()) fab.show();
396     }
397 }