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