]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/AccountSummary.java
color the swipe progress spinner in the accounts summary activity too
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / AccountSummary.java
1 /*
2  * Copyright © 2018 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;
19
20 import android.arch.lifecycle.ViewModelProviders;
21 import android.content.Intent;
22 import android.content.SharedPreferences;
23 import android.content.pm.PackageInfo;
24 import android.os.Build;
25 import android.os.Bundle;
26 import android.preference.PreferenceManager;
27 import android.support.annotation.NonNull;
28 import android.support.design.widget.FloatingActionButton;
29 import android.support.design.widget.Snackbar;
30 import android.support.v4.view.GravityCompat;
31 import android.support.v4.widget.DrawerLayout;
32 import android.support.v4.widget.SwipeRefreshLayout;
33 import android.support.v7.app.ActionBarDrawerToggle;
34 import android.support.v7.app.AppCompatActivity;
35 import android.support.v7.widget.LinearLayoutManager;
36 import android.support.v7.widget.RecyclerView;
37 import android.support.v7.widget.Toolbar;
38 import android.util.Log;
39 import android.view.Menu;
40 import android.view.MenuItem;
41 import android.view.View;
42 import android.widget.LinearLayout;
43
44 import net.ktnx.mobileledger.async.RetrieveAccountsTask;
45 import net.ktnx.mobileledger.model.LedgerAccount;
46 import net.ktnx.mobileledger.utils.MobileLedgerDatabase;
47
48 import java.lang.ref.WeakReference;
49 import java.util.Date;
50 import java.util.List;
51
52 import static net.ktnx.mobileledger.SettingsActivity.PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS;
53
54 public class AccountSummary extends AppCompatActivity {
55     DrawerLayout drawer;
56
57     private static long account_list_last_updated;
58     private static boolean account_list_needs_update = true;
59     MenuItem mShowHiddenAccounts;
60     SharedPreferences.OnSharedPreferenceChangeListener sBindPreferenceSummaryToValueListener;
61     private MobileLedgerDatabase dbh;
62     private AccountSummaryViewModel model;
63     private AccountSummaryAdapter modelAdapter;
64     private Menu optMenu;
65
66     public static void preferences_changed() {
67         account_list_needs_update = true;
68     }
69
70     @Override
71     protected void onCreate(Bundle savedInstanceState) {
72         super.onCreate(savedInstanceState);
73         setContentView(R.layout.activity_account_summary);
74         Toolbar toolbar = findViewById(R.id.toolbar);
75         setSupportActionBar(toolbar);
76
77         dbh = new MobileLedgerDatabase(this);
78
79         drawer = findViewById(R.id.drawer_layout);
80         ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
81                 this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
82         drawer.addDrawerListener(toggle);
83         toggle.syncState();
84
85         android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
86
87         try {
88             PackageInfo pi = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
89             ver.setText(pi.versionName);
90         } catch (Exception e) {
91             e.printStackTrace();
92         }
93
94         model = ViewModelProviders.of(this).get(AccountSummaryViewModel.class);
95         List<LedgerAccount> accounts = model.getAccounts();
96         modelAdapter = new AccountSummaryAdapter(accounts);
97
98         RecyclerView root = findViewById(R.id.account_root);
99         root.setAdapter(modelAdapter);
100
101         LinearLayoutManager llm = new LinearLayoutManager(this);
102         llm.setOrientation(LinearLayoutManager.VERTICAL);
103         root.setLayoutManager(llm);
104
105         root.addOnItemTouchListener(new RecyclerItemListener(this, root, new RecyclerItemListener.RecyclerTouchListener() {
106             @Override
107             public void onClickItem(View v, int position) {
108                 Log.d("list", String.format("item %d clicked", position));
109                 if (modelAdapter.isSelectionActive()) {
110                     modelAdapter.selectItem(position);
111                 }
112             }
113
114             @Override
115             public void onLongClickItem(View v, int position) {
116                 Log.d("list", String.format("item %d long-clicked", position));
117                 modelAdapter.startSelection();
118                 if (optMenu != null) {
119                     optMenu.findItem(R.id.menu_acc_summary_cancel_selection).setVisible(true);
120                     optMenu.findItem(R.id.menu_acc_summary_confirm_selection).setVisible(true);
121                     optMenu.findItem(R.id.menu_acc_summary_only_starred).setVisible(false);
122                 }
123                 {
124                     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.btn_add_transaction);
125                     if (fab != null) fab.hide();
126                 }
127             }
128         }));
129
130         root.addOnScrollListener(new RecyclerView.OnScrollListener() {
131             @Override
132             public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
133                 if (dy < 0) ((FloatingActionButton) findViewById(R.id.btn_add_transaction)).show();
134                 if (dy > 0) ((FloatingActionButton) findViewById(R.id.btn_add_transaction)).hide();
135             }
136         });
137         SwipeRefreshLayout swiper = findViewById(R.id.account_swiper);
138         swiper.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
139         swiper.setOnRefreshListener(() -> {
140             Log.d("ui", "refreshing accounts via swipe");
141             update_accounts(true);
142         });
143         prepare_db();
144 //        update_account_table();
145         update_accounts(false);
146     }
147
148     @Override
149     protected void onStart() {
150         super.onStart();
151         LinearLayout grp = drawer.findViewById(R.id.nav_actions);
152         for (int i = 0; i < grp.getChildCount(); i++) {
153             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
154                 grp.getChildAt(i).setBackgroundColor(
155                         getResources().getColor(R.color.drawer_background, getTheme()));
156             }
157             else {
158                 grp.getChildAt(i)
159                         .setBackgroundColor(getResources().getColor(R.color.drawer_background));
160             }
161         }
162         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
163             drawer.findViewById(R.id.nav_account_summary).setBackgroundColor(
164                     getResources().getColor(R.color.table_row_even_bg, getTheme()));
165         }
166         else {
167             drawer.findViewById(R.id.nav_account_summary)
168                     .setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
169         }
170     }
171
172     public void fab_new_transaction_clicked(View view) {
173         Intent intent = new Intent(this, NewTransactionActivity.class);
174         startActivity(intent);
175         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
176     }
177
178     public void nav_exit_clicked(View view) {
179         Log.w("app", "exiting");
180         finish();
181     }
182
183     public void nav_settings_clicked(View view) {
184         Intent intent = new Intent(this, SettingsActivity.class);
185         startActivity(intent);
186     }
187     public void onLatestTransactionsClicked(View view) {
188         Intent intent = new Intent(this, TransactionListActivity.class);
189         startActivity(intent);
190     }
191     @Override
192     public void onBackPressed() {
193         DrawerLayout drawer = findViewById(R.id.drawer_layout);
194         if (drawer.isDrawerOpen(GravityCompat.START)) {
195             drawer.closeDrawer(GravityCompat.START);
196         } else {
197             super.onBackPressed();
198         }
199     }
200
201     @Override
202     public boolean onCreateOptionsMenu(Menu menu) {
203         // Inflate the menu; this adds items to the action bar if it is present.
204         getMenuInflater().inflate(R.menu.account_summary, menu);
205         optMenu = menu;
206
207         mShowHiddenAccounts = menu.findItem(R.id.menu_acc_summary_only_starred);
208         if (mShowHiddenAccounts == null) throw new AssertionError();
209
210         sBindPreferenceSummaryToValueListener = (preference, value) -> mShowHiddenAccounts
211                 .setChecked(preference.getBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, false));
212         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
213         pref.registerOnSharedPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
214
215         mShowHiddenAccounts.setChecked(pref.getBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, false));
216
217         return true;
218     }
219
220     @Override
221     public boolean onOptionsItemSelected(MenuItem item) {
222         // Handle action bar item clicks here. The action bar will
223         // automatically handle clicks on the Home/Up button, so long
224         // as you specify a parent activity in AndroidManifest.xml.
225 //        int id = item.getItemId();
226
227         //noinspection SimplifiableIfStatement
228         //if (id == R.id.action_settings) {
229         //    return true;
230         // }
231
232         return super.onOptionsItemSelected(item);
233     }
234
235     public void onRefreshAccountSummaryClicked(MenuItem mi) {
236         update_accounts(true);
237     }
238
239     public
240     void onShowOnlyStarredClicked(MenuItem mi) {
241         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
242         boolean flag = pref.getBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, false);
243
244         SharedPreferences.Editor editor = pref.edit();
245         editor.putBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, !flag);
246         Log.d("pref", "Setting show only starred accounts pref to " + (flag ? "false" : "true"));
247         editor.apply();
248
249         update_account_table();
250     }
251
252     private void prepare_db() {
253         account_list_last_updated = dbh.get_option_value("last_refresh", (long) 0);
254     }
255
256     private void update_accounts(boolean force) {
257         long now = new Date().getTime();
258         if ((now > (account_list_last_updated + (24 * 3600*1000))) || force) {
259             Log.d("db", "accounts last updated at " + account_list_last_updated+" and now is " + now+". re-fetching");
260             update_accounts();
261         }
262     }
263
264     private void update_accounts() {
265         RetrieveAccountsTask task = new RetrieveAccountsTask(new WeakReference<>(this));
266
267         task.setPref(PreferenceManager.getDefaultSharedPreferences(this));
268         task.execute();
269
270     }
271     public void onAccountRefreshDone(int error) {
272         SwipeRefreshLayout srl = findViewById(R.id.account_swiper);
273         srl.setRefreshing(false);
274         if (error != 0) {
275             String err_text = getResources().getString(error);
276             Log.d("visual", String.format("showing snackbar: %s", err_text));
277             Snackbar.make(drawer, err_text, Snackbar.LENGTH_LONG ).show();
278         }
279         else {
280             dbh.set_option_value("last_refresh", new Date().getTime() );
281             update_account_table();
282         }
283     }
284     private void update_account_table() {
285         model.reloadAccounts();
286         modelAdapter.notifyDataSetChanged();
287     }
288     void stopSelection() {
289         modelAdapter.stopSelection();
290         if (optMenu != null) {
291             optMenu.findItem(R.id.menu_acc_summary_cancel_selection).setVisible(false);
292             optMenu.findItem(R.id.menu_acc_summary_confirm_selection).setVisible(false);
293             optMenu.findItem(R.id.menu_acc_summary_only_starred).setVisible(true);
294         }
295         {
296             FloatingActionButton fab = findViewById(R.id.btn_add_transaction);
297             if (fab != null) fab.show();
298         }
299     }
300     public void onCancelAccSelection(MenuItem item) {
301         stopSelection();
302     }
303     public void onConfirmAccSelection(MenuItem item) {
304         model.commitSelections();
305         stopSelection();
306     }
307 }