]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
some lambdas
[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.preference.PreferenceManager;
25 import android.support.annotation.ColorInt;
26 import android.support.v4.app.FragmentManager;
27 import android.support.v4.app.FragmentTransaction;
28 import android.support.v4.view.GravityCompat;
29 import android.support.v4.widget.DrawerLayout;
30 import android.support.v7.app.ActionBarDrawerToggle;
31 import android.support.v7.app.AppCompatActivity;
32 import android.support.v7.widget.Toolbar;
33 import android.util.Log;
34 import android.view.ContextMenu;
35 import android.view.MenuItem;
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.RetrieveTransactionsTask;
43 import net.ktnx.mobileledger.model.Data;
44 import net.ktnx.mobileledger.model.LedgerAccount;
45 import net.ktnx.mobileledger.ui.MobileLedgerListFragment;
46 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
47 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
48 import net.ktnx.mobileledger.utils.MLDB;
49
50 import java.lang.ref.WeakReference;
51 import java.time.ZoneId;
52 import java.time.format.DateTimeFormatter;
53 import java.util.Date;
54 import java.util.Observable;
55 import java.util.Observer;
56
57 public class MainActivity extends AppCompatActivity {
58     public MobileLedgerListFragment currentFragment = null;
59     DrawerLayout drawer;
60     private AccountSummaryFragment accountSummaryFragment;
61     private TransactionListFragment transactionListFragment;
62     private FragmentManager fragmentManager;
63     private TextView tvLastUpdate;
64     private RetrieveTransactionsTask retrieveTransactionsTask;
65     private View bTransactionListCancelDownload;
66     private ProgressBar progressBar;
67     private LinearLayout progressLayout;
68
69     @Override
70     protected void onCreate(Bundle savedInstanceState) {
71         super.onCreate(savedInstanceState);
72         setContentView(R.layout.activity_main);
73         Toolbar toolbar = findViewById(R.id.toolbar);
74         setSupportActionBar(toolbar);
75
76         drawer = findViewById(R.id.drawer_layout);
77         ActionBarDrawerToggle toggle =
78                 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
79                         R.string.navigation_drawer_close);
80         drawer.addDrawerListener(toggle);
81         toggle.syncState();
82
83         android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
84
85         try {
86             PackageInfo pi =
87                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
88             ver.setText(pi.versionName);
89         }
90         catch (Exception e) {
91             e.printStackTrace();
92         }
93
94         tvLastUpdate = findViewById(R.id.transactions_last_update);
95
96         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
97         progressBar = findViewById(R.id.transaction_list_progress_bar);
98         if (progressBar == null)
99             throw new RuntimeException("Can't get hold on the transaction value progress bar");
100         progressLayout = findViewById(R.id.transaction_progress_layout);
101         if (progressLayout == null) throw new RuntimeException(
102                 "Can't get hold on the transaction value progress bar layout");
103
104         fragmentManager = getSupportFragmentManager();
105
106         onAccountSummaryClicked(null);
107
108         Data.lastUpdateDate.addObserver(new Observer() {
109             @Override
110             public void update(Observable o, Object arg) {
111                 Log.d("main", "lastUpdateDate changed");
112                 runOnUiThread(() -> {
113                     Date date = Data.lastUpdateDate.get();
114                     if (date == null) {
115                         tvLastUpdate.setText(R.string.transaction_last_update_never);
116                     }
117                     else {
118                         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
119                             tvLastUpdate.setText(date.toInstant().atZone(ZoneId.systemDefault())
120                                     .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
121                         }
122                         else {
123                             tvLastUpdate.setText(date.toLocaleString());
124                         }
125                     }
126                 });
127             }
128         });
129
130         updateLastUpdateTextFromDB();
131         Date lastUpdate = Data.lastUpdateDate.get();
132
133         long now = new Date().getTime();
134         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
135             if (lastUpdate == null) Log.d("db", "WEB data never fetched. scheduling a fetch");
136             else Log.d("db",
137                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
138                             lastUpdate.getTime() / 1000f, now / 1000f));
139
140             scheduleTransactionListRetrieval();
141         }
142     }
143     public void fab_new_transaction_clicked(View view) {
144         Intent intent = new Intent(this, NewTransactionActivity.class);
145         startActivity(intent);
146         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
147     }
148
149     public void nav_exit_clicked(View view) {
150         Log.w("app", "exiting");
151         finish();
152     }
153
154     public void nav_settings_clicked(View view) {
155         Intent intent = new Intent(this, SettingsActivity.class);
156         startActivity(intent);
157     }
158     public void markDrawerItemCurrent(int id) {
159         TextView item = drawer.findViewById(id);
160         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
161             item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
162         }
163         else {
164             item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
165         }
166
167         setTitle(item.getText());
168
169         @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
170
171         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
172         for (int i = 0; i < actions.getChildCount(); i++) {
173             View view = actions.getChildAt(i);
174             if (view.getId() != id) {
175                 view.setBackgroundColor(transparent);
176             }
177         }
178     }
179     public void onOptionsMenuClicked(MenuItem menuItem) {
180         ContextMenu.ContextMenuInfo info = menuItem.getMenuInfo();
181         switch (menuItem.getItemId()) {
182             case R.id.menu_acc_summary_cancel_selection:
183                 if (accountSummaryFragment != null)
184                     accountSummaryFragment.onCancelAccSelection(menuItem);
185                 break;
186             case R.id.menu_acc_summary_confirm_selection:
187                 if (accountSummaryFragment != null)
188                     accountSummaryFragment.onConfirmAccSelection(menuItem);
189                 break;
190             case R.id.menu_acc_summary_only_starred:
191                 if (accountSummaryFragment != null)
192                     accountSummaryFragment.onShowOnlyStarredClicked(menuItem);
193                 break;
194             case R.id.menu_transaction_list_filter:
195                 if (transactionListFragment != null)
196                     transactionListFragment.onShowFilterClick(menuItem);
197                 break;
198             default:
199                 Log.e("menu", String.format("Menu item %d not handled", menuItem.getItemId()));
200         }
201     }
202     public void onViewClicked(View view) {
203         switch (view.getId()) {
204             case R.id.clearAccountNameFilter:
205                 if (transactionListFragment != null)
206                     transactionListFragment.onClearAccountNameClick(view);
207                 break;
208             default:
209                 Log.e("click", String.format("View %d click not handled", view.getId()));
210         }
211     }
212     public void onAccountSummaryClicked(View view) {
213         drawer.closeDrawers();
214
215         resetFragmentBackStack();
216
217         showAccountSummaryFragment();
218     }
219     private void showAccountSummaryFragment() {
220         FragmentTransaction ft = fragmentManager.beginTransaction();
221         accountSummaryFragment = new AccountSummaryFragment();
222         ft.replace(R.id.root_frame, accountSummaryFragment);
223         ft.commit();
224         currentFragment = accountSummaryFragment;
225     }
226     public void onLatestTransactionsClicked(View view) {
227         drawer.closeDrawers();
228
229         resetFragmentBackStack();
230
231         showTransactionsFragment(null);
232     }
233     private void resetFragmentBackStack() {
234 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
235     }
236     private void showTransactionsFragment(LedgerAccount account) {
237         FragmentTransaction ft = fragmentManager.beginTransaction();
238         if (transactionListFragment == null) {
239             Log.d("flow", "MainActivity creating TransactionListFragment");
240             transactionListFragment = new TransactionListFragment();
241         }
242         Bundle bundle = new Bundle();
243         if (account != null) {
244             bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
245                     account.getName());
246         }
247         transactionListFragment.setArguments(bundle);
248         ft.replace(R.id.root_frame, transactionListFragment);
249         if (account != null)
250             ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
251         ft.commit();
252
253         currentFragment = transactionListFragment;
254     }
255     public void showAccountTransactions(LedgerAccount account) {
256         showTransactionsFragment(account);
257     }
258     @Override
259     public void onBackPressed() {
260         DrawerLayout drawer = findViewById(R.id.drawer_layout);
261         if (drawer.isDrawerOpen(GravityCompat.START)) {
262             drawer.closeDrawer(GravityCompat.START);
263         }
264         else {
265             Log.d("fragments",
266                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
267
268             super.onBackPressed();
269         }
270     }
271     public void updateLastUpdateTextFromDB() {
272         {
273             long last_update = MLDB.get_option_value(MLDB.OPT_TRANSACTION_LIST_STAMP, 0L);
274
275             Log.d("transactions", String.format("Last update = %d", last_update));
276             if (last_update == 0) {
277                 Data.lastUpdateDate.set(null);
278             }
279             else {
280                 Data.lastUpdateDate.set(new Date(last_update));
281             }
282         }
283     }
284     public void scheduleTransactionListRetrieval() {
285         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
286
287         RetrieveTransactionsTask.Params params = new RetrieveTransactionsTask.Params(
288                 PreferenceManager.getDefaultSharedPreferences(this));
289
290         retrieveTransactionsTask.execute(params);
291         bTransactionListCancelDownload.setEnabled(true);
292     }
293     public void onStopTransactionRefreshClick(View view) {
294         Log.d("interactive", "Cancelling transactions refresh");
295         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
296         bTransactionListCancelDownload.setEnabled(false);
297     }
298     public void onRetrieveDone(boolean success) {
299         progressLayout.setVisibility(View.GONE);
300         updateLastUpdateTextFromDB();
301     }
302     public void onRetrieveStart() {
303         progressBar.setIndeterminate(true);
304         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
305         else progressBar.setProgress(0);
306         progressLayout.setVisibility(View.VISIBLE);
307     }
308     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
309         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
310             (progress.getTotal() == 0))
311         {
312             progressBar.setIndeterminate(true);
313         }
314         else {
315             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
316                 progressBar.setMin(0);
317             }
318             progressBar.setMax(progress.getTotal());
319             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
320                 progressBar.setProgress(progress.getProgress(), true);
321             }
322             else progressBar.setProgress(progress.getProgress());
323             progressBar.setIndeterminate(false);
324         }
325     }
326
327 }