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