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