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