]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
keep the new transaction FAB hidden when the profile doesn't permit new transactions
[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()) fab.show();
101                 else fab.hide();
102             });
103         });
104
105         drawer = findViewById(R.id.drawer_layout);
106         ActionBarDrawerToggle toggle =
107                 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
108                         R.string.navigation_drawer_close);
109         drawer.addDrawerListener(toggle);
110         toggle.syncState();
111
112         TextView ver = drawer.findViewById(R.id.drawer_version_text);
113
114         try {
115             PackageInfo pi =
116                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
117             ver.setText(pi.versionName);
118         }
119         catch (Exception e) {
120             e.printStackTrace();
121         }
122
123         tvLastUpdate = findViewById(R.id.transactions_last_update);
124
125         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
126         progressBar = findViewById(R.id.transaction_list_progress_bar);
127         if (progressBar == null)
128             throw new RuntimeException("Can't get hold on the transaction value progress bar");
129         progressLayout = findViewById(R.id.transaction_progress_layout);
130         if (progressLayout == null) throw new RuntimeException(
131                 "Can't get hold on the transaction value progress bar layout");
132
133         fragmentManager = getSupportFragmentManager();
134         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
135
136         markDrawerItemCurrent(R.id.nav_account_summary);
137
138         mViewPager = findViewById(R.id.root_frame);
139         mViewPager.setAdapter(mSectionsPagerAdapter);
140         mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
141             @Override
142             public void onPageSelected(int position) {
143                 switch (position) {
144                     case 0:
145                         markDrawerItemCurrent(R.id.nav_account_summary);
146                         break;
147                     case 1:
148                         markDrawerItemCurrent(R.id.nav_latest_transactions);
149                         break;
150                     default:
151                         Log.e("MainActivity", String.format("Unexpected page index %d", position));
152                 }
153
154                 super.onPageSelected(position);
155             }
156         });
157
158         Data.lastUpdateDate.addObserver((o, arg) -> {
159             Log.d("main", "lastUpdateDate changed");
160             runOnUiThread(() -> {
161                 Date date = Data.lastUpdateDate.get();
162                 if (date == null) {
163                     tvLastUpdate.setText(R.string.transaction_last_update_never);
164                 }
165                 else {
166                     final String text = DateFormat.getDateTimeInstance().format(date);
167                     tvLastUpdate.setText(text);
168                     Log.d("despair", String.format("Date formatted: %s", text));
169                 }
170             });
171         });
172
173         findViewById(R.id.btn_no_profiles_add).setOnClickListener(v -> startAddProfileActivity());
174
175         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
176     }
177     @Override
178     protected void onResume() {
179         super.onResume();
180         setupProfile();
181     }
182     private void startAddProfileActivity() {
183         Intent intent = new Intent(this, ProfileListActivity.class);
184         Bundle args = new Bundle();
185         args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
186         args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, ProfileListActivity.PROFILE_INDEX_NONE);
187         intent.putExtras(args);
188         startActivity(intent, args);
189     }
190     private void setupProfile() {
191         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
192         MobileLedgerProfile profile;
193
194         profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
195
196         if (Data.profiles.getList().isEmpty()) {
197             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
198             findViewById(R.id.pager_layout).setVisibility(View.GONE);
199             return;
200         }
201
202         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
203         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
204
205         if (profile == null) profile = Data.profiles.get(0);
206
207         if (profile == null) throw new AssertionError("profile must have a value");
208
209         Data.setCurrentProfile(profile);
210     }
211     public void fabNewTransactionClicked(View view) {
212         Intent intent = new Intent(this, NewTransactionActivity.class);
213         startActivity(intent);
214         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
215     }
216     public void navSettingsClicked(View view) {
217         Intent intent = new Intent(this, SettingsActivity.class);
218         startActivity(intent);
219         drawer.closeDrawers();
220     }
221     public void markDrawerItemCurrent(int id) {
222         TextView item = drawer.findViewById(id);
223         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
224             item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg, getTheme()));
225         }
226         else {
227             item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg));
228         }
229
230         @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
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(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.setIndeterminate(true);
339         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
340         else progressBar.setProgress(0);
341         progressLayout.setVisibility(View.VISIBLE);
342     }
343     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
344         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
345             (progress.getTotal() == 0))
346         {
347             progressBar.setIndeterminate(true);
348         }
349         else {
350             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
351                 progressBar.setMin(0);
352             }
353             progressBar.setMax(progress.getTotal());
354             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
355                 progressBar.setProgress(progress.getProgress(), true);
356             }
357             else progressBar.setProgress(progress.getProgress());
358             progressBar.setIndeterminate(false);
359         }
360     }
361     public void navProfilesClicked(View view) {
362         drawer.closeDrawers();
363         Intent intent = new Intent(this, ProfileListActivity.class);
364         startActivity(intent);
365     }
366     public class SectionsPagerAdapter extends FragmentPagerAdapter {
367
368         public SectionsPagerAdapter(FragmentManager fm) {
369             super(fm);
370         }
371
372         @Override
373         public Fragment getItem(int position) {
374             Log.d("main", String.format("Switching to fragment %d", position));
375             switch (position) {
376                 case 0:
377                     return new AccountSummaryFragment();
378                 case 1:
379                     return new TransactionListFragment();
380                 default:
381                     throw new IllegalStateException(
382                             String.format("Unexpected fragment index: " + "%d", position));
383             }
384         }
385
386         @Override
387         public int getCount() {
388             return 2;
389         }
390     }
391     public void fabShouldShow() {
392         MobileLedgerProfile profile = Data.profile.get();
393         if (profile.isPostingPermitted()) fab.show();
394     }
395 }