]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
use date formatted that hopefully uses the system locale properly
[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.SharedPreferences;
22 import android.content.pm.PackageInfo;
23 import android.os.Build;
24 import android.os.Bundle;
25 import android.support.annotation.ColorInt;
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
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.MobileLedgerListFragment;
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     public MobileLedgerListFragment currentFragment = null;
58     DrawerLayout drawer;
59     private AccountSummaryFragment accountSummaryFragment;
60     private TransactionListFragment transactionListFragment;
61     private FragmentManager fragmentManager;
62     private TextView tvLastUpdate;
63     private RetrieveTransactionsTask retrieveTransactionsTask;
64     private View bTransactionListCancelDownload;
65     private ProgressBar progressBar;
66     private LinearLayout progressLayout;
67     private SectionsPagerAdapter mSectionsPagerAdapter;
68     private ViewPager mViewPager;
69
70     @Override
71     protected void onStart() {
72         super.onStart();
73
74         Data.lastUpdateDate.set(null);
75         updateLastUpdateTextFromDB();
76         Date lastUpdate = Data.lastUpdateDate.get();
77
78         long now = new Date().getTime();
79         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
80             if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
81             else Log.d("db",
82                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
83                             lastUpdate.getTime() / 1000f, now / 1000f));
84
85             scheduleTransactionListRetrieval();
86         }
87     }
88     @Override
89     protected void onCreate(Bundle savedInstanceState) {
90         super.onCreate(savedInstanceState);
91         setContentView(R.layout.activity_main);
92         Toolbar toolbar = findViewById(R.id.toolbar);
93         setSupportActionBar(toolbar);
94
95         Data.profile.addObserver((o, arg) -> {
96             MobileLedgerProfile profile = Data.profile.get();
97             runOnUiThread(() -> {
98                 if (profile == null) toolbar.setSubtitle("");
99                 else toolbar.setSubtitle(profile.getName());
100             });
101         });
102
103         setupProfile();
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         android.widget.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         mViewPager = findViewById(R.id.root_frame);
137         mViewPager.setAdapter(mSectionsPagerAdapter);
138         mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
139             @Override
140             public void onPageSelected(int position) {
141                 switch (position) {
142                     case 0:
143                         markDrawerItemCurrent(R.id.nav_account_summary);
144                         break;
145                     case 1:
146                         markDrawerItemCurrent(R.id.nav_latest_transactions);
147                         break;
148                     default:
149                         Log.e("MainActivity", String.format("Unexpected page index %d", position));
150                 }
151
152                 super.onPageSelected(position);
153             }
154         });
155
156         Data.lastUpdateDate.addObserver((o, arg) -> {
157             Log.d("main", "lastUpdateDate changed");
158             runOnUiThread(() -> {
159                 Date date = Data.lastUpdateDate.get();
160                 if (date == null) {
161                     tvLastUpdate.setText(R.string.transaction_last_update_never);
162                 }
163                 else {
164                     final String text = DateFormat.getDateTimeInstance().format(date);
165                     tvLastUpdate.setText(text);
166                     Log.d("despair", String.format("Date formatted: %s", text));
167                 }
168             });
169         });
170     }
171     private void setupProfile() {
172         Data.profiles.setList(MobileLedgerProfile.loadAllFromDB());
173         MobileLedgerProfile profile = null;
174
175         String profileUUID = MLDB.get_option_value(MLDB.OPT_PROFILE_UUID, null);
176         if (profileUUID == null) {
177             if (Data.profiles.isEmpty()) {
178                 Data.profiles.setList(MobileLedgerProfile.createInitialProfileList());
179                 profile = Data.profiles.get(0);
180
181                 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
182                 Log.d("profiles", "Migrating from preferences to profiles");
183                 // migration to multiple profiles
184                 if (profile.getUrl().isEmpty()) {
185                     // no legacy config
186                     Intent intent = new Intent(this, ProfileListActivity.class);
187                     startActivity(intent);
188                 }
189                 profile.setUrl(backend.getString("backend_url", ""));
190                 profile.setAuthEnabled(backend.getBoolean("backend_use_http_auth", false));
191                 profile.setAuthUserName(backend.getString("backend_auth_user", null));
192                 profile.setAuthPassword(backend.getString("backend_auth_password", null));
193                 profile.storeInDB();
194                 SharedPreferences.Editor editor = backend.edit();
195                 editor.clear();
196                 editor.apply();
197             }
198         }
199         else {
200             profile = MobileLedgerProfile.loadUUIDFromDB(profileUUID);
201         }
202
203         if (profile == null) profile = Data.profiles.get(0);
204
205         if (profile == null) throw new AssertionError("profile must have a value");
206
207         Data.setCurrentProfile(profile);
208
209         if (profile.getUrl().isEmpty()) {
210             Intent intent = new Intent(this, ProfileListActivity.class);
211             Bundle args = new Bundle();
212             args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
213             args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, 0);
214             intent.putExtras(args);
215             startActivity(intent, args);
216         }
217     }
218     public void fab_new_transaction_clicked(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
224     public void nav_exit_clicked(View view) {
225         Log.w("app", "exiting");
226         finish();
227     }
228
229     public void nav_settings_clicked(View view) {
230         Intent intent = new Intent(this, SettingsActivity.class);
231         startActivity(intent);
232         drawer.closeDrawers();
233     }
234     public void markDrawerItemCurrent(int id) {
235         TextView item = drawer.findViewById(id);
236         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
237             item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
238         }
239         else {
240             item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
241         }
242
243         setTitle(item.getText());
244
245         @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
246
247         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
248         for (int i = 0; i < actions.getChildCount(); i++) {
249             View view = actions.getChildAt(i);
250             if (view.getId() != id) {
251                 view.setBackgroundColor(transparent);
252             }
253         }
254     }
255     public void onViewClicked(View view) {
256         switch (view.getId()) {
257             case R.id.clearAccountNameFilter:
258                 if (transactionListFragment != null)
259                     transactionListFragment.onClearAccountNameClick(view);
260                 break;
261             default:
262                 Log.e("click", String.format("View %d click not handled", view.getId()));
263         }
264     }
265     public void onAccountSummaryClicked(View view) {
266         drawer.closeDrawers();
267
268         showAccountSummaryFragment();
269     }
270     private void showAccountSummaryFragment() {
271         mViewPager.setCurrentItem(0, true);
272 //        FragmentTransaction ft = fragmentManager.beginTransaction();
273 //        accountSummaryFragment = new AccountSummaryFragment();
274 //        ft.replace(R.id.root_frame, accountSummaryFragment);
275 //        ft.commit();
276 //        currentFragment = accountSummaryFragment;
277     }
278     public void onLatestTransactionsClicked(View view) {
279         drawer.closeDrawers();
280
281         showTransactionsFragment(null);
282     }
283     private void resetFragmentBackStack() {
284 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
285     }
286     private void showTransactionsFragment(LedgerAccount account) {
287         mViewPager.setCurrentItem(1, true);
288 //        FragmentTransaction ft = fragmentManager.beginTransaction();
289 //        if (transactionListFragment == null) {
290 //            Log.d("flow", "MainActivity creating TransactionListFragment");
291 //            transactionListFragment = new TransactionListFragment();
292 //        }
293 //        Bundle bundle = new Bundle();
294 //        if (account != null) {
295 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
296 //                    account.getName());
297 //        }
298 //        transactionListFragment.setArguments(bundle);
299 //        ft.replace(R.id.root_frame, transactionListFragment);
300 //        if (account != null)
301 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
302 //        ft.commit();
303 //
304 //        currentFragment = transactionListFragment;
305     }
306     public void showAccountTransactions(LedgerAccount account) {
307         showTransactionsFragment(account);
308     }
309     @Override
310     public void onBackPressed() {
311         DrawerLayout drawer = findViewById(R.id.drawer_layout);
312         if (drawer.isDrawerOpen(GravityCompat.START)) {
313             drawer.closeDrawer(GravityCompat.START);
314         }
315         else {
316             Log.d("fragments",
317                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
318
319             super.onBackPressed();
320         }
321     }
322     public void updateLastUpdateTextFromDB() {
323         {
324             long last_update = Data.profile.get().get_option_value(MLDB.OPT_LAST_SCRAPE, 0L);
325
326             Log.d("transactions", String.format("Last update = %d", last_update));
327             if (last_update == 0) {
328                 Data.lastUpdateDate.set(null);
329             }
330             else {
331                 Data.lastUpdateDate.set(new Date(last_update));
332             }
333         }
334     }
335     public void scheduleTransactionListRetrieval() {
336         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
337
338         retrieveTransactionsTask.execute();
339         bTransactionListCancelDownload.setEnabled(true);
340     }
341     public void onStopTransactionRefreshClick(View view) {
342         Log.d("interactive", "Cancelling transactions refresh");
343         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
344         bTransactionListCancelDownload.setEnabled(false);
345     }
346     public void onRetrieveDone(boolean success) {
347         progressLayout.setVisibility(View.GONE);
348         updateLastUpdateTextFromDB();
349
350         new RefreshDescriptionsTask().execute();
351     }
352     public void onRetrieveStart() {
353         progressBar.setIndeterminate(true);
354         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
355         else progressBar.setProgress(0);
356         progressLayout.setVisibility(View.VISIBLE);
357     }
358     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
359         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
360             (progress.getTotal() == 0))
361         {
362             progressBar.setIndeterminate(true);
363         }
364         else {
365             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
366                 progressBar.setMin(0);
367             }
368             progressBar.setMax(progress.getTotal());
369             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
370                 progressBar.setProgress(progress.getProgress(), true);
371             }
372             else progressBar.setProgress(progress.getProgress());
373             progressBar.setIndeterminate(false);
374         }
375     }
376     public void nav_profiles_clicked(View view) {
377         drawer.closeDrawers();
378         Intent intent = new Intent(this, ProfileListActivity.class);
379         startActivity(intent);
380     }
381     public class SectionsPagerAdapter extends FragmentPagerAdapter {
382
383         public SectionsPagerAdapter(FragmentManager fm) {
384             super(fm);
385         }
386
387         @Override
388         public Fragment getItem(int position) {
389             Log.d("main", String.format("Switching to gragment %d", position));
390             switch (position) {
391                 case 0:
392                     return new AccountSummaryFragment();
393                 case 1:
394                     return new TransactionListFragment();
395                 default:
396                     throw new IllegalStateException(
397                             String.format("Unexpected fragment index: " + "%d", position));
398             }
399         }
400
401         @Override
402         public int getCount() {
403             return 2;
404         }
405     }
406
407 }