3a09f2bbde2cc5d90ad5196eb19520b871f4c46f
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / account_summary / AccountSummaryFragment.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.ui.account_summary;
19
20 import android.arch.lifecycle.ViewModelProviders;
21 import android.content.Context;
22 import android.content.SharedPreferences;
23 import android.os.Bundle;
24 import android.preference.PreferenceManager;
25 import android.support.annotation.NonNull;
26 import android.support.annotation.Nullable;
27 import android.support.design.widget.FloatingActionButton;
28 import android.support.design.widget.Snackbar;
29 import android.support.v4.app.Fragment;
30 import android.support.v4.widget.SwipeRefreshLayout;
31 import android.support.v7.widget.LinearLayoutManager;
32 import android.support.v7.widget.RecyclerView;
33 import android.util.Log;
34 import android.view.LayoutInflater;
35 import android.view.Menu;
36 import android.view.MenuInflater;
37 import android.view.MenuItem;
38 import android.view.View;
39 import android.view.ViewGroup;
40
41 import net.ktnx.mobileledger.R;
42 import net.ktnx.mobileledger.ui.RecyclerItemListener;
43 import net.ktnx.mobileledger.async.RetrieveAccountsTask;
44 import net.ktnx.mobileledger.model.LedgerAccount;
45 import net.ktnx.mobileledger.ui.activity.MainActivity;
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.ui.activity.SettingsActivity.PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS;
53
54 public class AccountSummaryFragment extends Fragment {
55
56     private static long account_list_last_updated;
57     private static boolean account_list_needs_update = true;
58     MenuItem mShowHiddenAccounts;
59     SharedPreferences.OnSharedPreferenceChangeListener sBindPreferenceSummaryToValueListener;
60     private AccountSummaryViewModel model;
61     private AccountSummaryAdapter modelAdapter;
62     private Menu optMenu;
63     private MainActivity mActivity;
64     private FloatingActionButton fab;
65     private SwipeRefreshLayout swiper;
66     @Override
67     public void onCreate(@Nullable Bundle savedInstanceState) {
68         super.onCreate(savedInstanceState);
69         setHasOptionsMenu(true);
70     }
71     public void onAttach(Context context) {
72         super.onAttach(context);
73         mActivity = (MainActivity) context;
74     }
75     @Override
76     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
77                              @Nullable Bundle savedInstanceState) {
78         return inflater.inflate(R.layout.account_summary_fragment, container, false);
79     }
80
81     @Override
82     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
83         super.onActivityCreated(savedInstanceState);
84
85         mActivity.markDrawerItemCurrent(R.id.nav_account_summary);
86
87         model = ViewModelProviders.of(this).get(AccountSummaryViewModel.class);
88         List<LedgerAccount> accounts = model.getAccounts(this.getContext());
89         modelAdapter = new AccountSummaryAdapter(accounts);
90
91         RecyclerView root = mActivity.findViewById(R.id.account_root);
92         root.setAdapter(modelAdapter);
93
94         LinearLayoutManager llm = new LinearLayoutManager(mActivity);
95         llm.setOrientation(LinearLayoutManager.VERTICAL);
96         root.setLayoutManager(llm);
97
98         fab = mActivity.findViewById(R.id.btn_add_transaction);
99
100         root.addOnItemTouchListener(new RecyclerItemListener(mActivity, root,
101                 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                         else {
109                             List<LedgerAccount> accounts = model.getAccounts(mActivity);
110                             if (accounts != null) {
111                                 LedgerAccount account = accounts.get(position);
112
113                                 mActivity.showAccountTransactions(account);
114                             }
115                         }
116                     }
117
118                     @Override
119                     public void onLongClickItem(View v, int position) {
120                         Log.d("list", String.format("item %d long-clicked", position));
121                         modelAdapter.startSelection();
122                         if (optMenu != null) {
123                             optMenu.findItem(R.id.menu_acc_summary_cancel_selection)
124                                     .setVisible(true);
125                             optMenu.findItem(R.id.menu_acc_summary_confirm_selection)
126                                     .setVisible(true);
127                             optMenu.findItem(R.id.menu_acc_summary_only_starred).setVisible(false);
128                         }
129                         {
130                             if (fab != null) fab.hide();
131                         }
132                     }
133                 }));
134
135         root.addOnScrollListener(new RecyclerView.OnScrollListener() {
136             @Override
137             public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
138                 if (fab != null) {
139                     if (dy < 0) fab.show();
140                     if (dy > 0) fab.hide();
141                 }
142             }
143         });
144         swiper = mActivity.findViewById(R.id.account_swiper);
145         swiper.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
146         swiper.setOnRefreshListener(() -> {
147             Log.d("ui", "refreshing accounts via swipe");
148             update_accounts(true);
149         });
150         prepare_db();
151 //        update_account_table();
152         update_accounts(false);
153
154     }
155     private void prepare_db() {
156         account_list_last_updated = MLDB.get_option_value(mActivity, "last_refresh", (long) 0);
157     }
158
159     private void update_accounts(boolean force) {
160         long now = new Date().getTime();
161         if ((now > (account_list_last_updated + (24 * 3600 * 1000))) || force) {
162             Log.d("db",
163                     "accounts last updated at " + account_list_last_updated + " and now is " + now +
164                     ". re-fetching");
165             update_accounts();
166         }
167     }
168
169     private void update_accounts() {
170         RetrieveAccountsTask task = new RetrieveAccountsTask(new WeakReference<>(this));
171
172         task.setPref(PreferenceManager.getDefaultSharedPreferences(mActivity));
173         task.execute();
174
175     }
176     public void onAccountRefreshDone(int error) {
177         swiper.setRefreshing(false);
178         if (error != 0) {
179             String err_text = getResources().getString(error);
180             Log.d("visual", String.format("showing snackbar: %s", err_text));
181             Snackbar.make(swiper, err_text, Snackbar.LENGTH_LONG).show();
182         }
183         else {
184             MLDB.set_option_value(mActivity, "last_refresh", new Date().getTime());
185             update_account_table();
186         }
187     }
188     private void update_account_table() {
189         if (this.getContext() == null) return;
190
191         model.reloadAccounts(this.getContext());
192         modelAdapter.notifyDataSetChanged();
193     }
194     public void onRefreshAccountSummaryClicked(MenuItem mi) {
195         update_accounts(true);
196     }
197
198     public void onShowOnlyStarredClicked(MenuItem mi) {
199         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mActivity);
200         boolean flag = pref.getBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, false);
201
202         SharedPreferences.Editor editor = pref.edit();
203         editor.putBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, !flag);
204         Log.d("pref", "Setting show only starred accounts pref to " + (flag ? "false" : "true"));
205         editor.apply();
206
207         update_account_table();
208     }
209
210     void stopSelection() {
211         modelAdapter.stopSelection();
212         if (optMenu != null) {
213             optMenu.findItem(R.id.menu_acc_summary_cancel_selection).setVisible(false);
214             optMenu.findItem(R.id.menu_acc_summary_confirm_selection).setVisible(false);
215             optMenu.findItem(R.id.menu_acc_summary_only_starred).setVisible(true);
216         }
217         {
218             if (fab != null) fab.show();
219         }
220     }
221     public void onCancelAccSelection(MenuItem item) {
222         stopSelection();
223     }
224     public void onConfirmAccSelection(MenuItem item) {
225         model.commitSelections(mActivity);
226         stopSelection();
227     }
228     @Override
229     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
230         // Inflate the menu; this adds items to the action bar if it is present.
231         inflater.inflate(R.menu.account_summary, menu);
232         optMenu = menu;
233
234         mShowHiddenAccounts = menu.findItem(R.id.menu_acc_summary_only_starred);
235         if (mShowHiddenAccounts == null) throw new AssertionError();
236
237         sBindPreferenceSummaryToValueListener = (preference, value) -> mShowHiddenAccounts
238                 .setChecked(preference.getBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, false));
239         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mActivity);
240         pref.registerOnSharedPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
241
242         mShowHiddenAccounts.setChecked(pref.getBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, false));
243
244         Log.d("menu", "MainActivity: onCreateOptionsMenu called");
245     }
246 }