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