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