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