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