]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/AccountSummary.java
411d96197e5e7627a5c7fe7cc453a897243eeeee
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / AccountSummary.java
1 package net.ktnx.mobileledger;
2
3 import android.annotation.SuppressLint;
4 import android.content.Intent;
5 import android.content.SharedPreferences;
6 import android.content.pm.PackageInfo;
7 import android.content.res.Resources;
8 import android.database.Cursor;
9 import android.graphics.Typeface;
10 import android.os.Build;
11 import android.os.Bundle;
12 import android.preference.PreferenceManager;
13 import android.support.design.widget.Snackbar;
14 import android.support.v4.view.GravityCompat;
15 import android.support.v4.widget.DrawerLayout;
16 import android.support.v7.app.ActionBarDrawerToggle;
17 import android.support.v7.app.AppCompatActivity;
18 import android.support.v7.widget.Toolbar;
19 import android.util.Log;
20 import android.util.TypedValue;
21 import android.view.ContextMenu;
22 import android.view.Gravity;
23 import android.view.Menu;
24 import android.view.MenuItem;
25 import android.view.View;
26 import android.view.ViewGroup;
27 import android.widget.EditText;
28 import android.widget.LinearLayout;
29 import android.widget.ProgressBar;
30 import android.widget.TextView;
31
32 import java.util.Date;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35
36 import static android.view.View.GONE;
37 import static net.ktnx.mobileledger.MobileLedgerDB.db;
38 import static net.ktnx.mobileledger.MobileLedgerDB.set_option_value;
39
40 public class AccountSummary extends AppCompatActivity {
41     DrawerLayout drawer;
42
43     private static long account_list_last_updated;
44     private static boolean account_list_needs_update = true;
45     MenuItem mShowHiddenAccounts;
46     SharedPreferences.OnSharedPreferenceChangeListener sBindPreferenceSummaryToValueListener;
47     private AccountRowLayout clickedAccountRow;
48
49     public static void preferences_changed() {
50         account_list_needs_update = true;
51     }
52     MenuItem mRefresh;
53
54     @Override
55     protected void onCreate(Bundle savedInstanceState) {
56         super.onCreate(savedInstanceState);
57         setContentView(R.layout.activity_account_summary);
58         Toolbar toolbar = findViewById(R.id.toolbar);
59         setSupportActionBar(toolbar);
60
61         drawer = findViewById(R.id.drawer_layout);
62         ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
63                 this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
64         drawer.addDrawerListener(toggle);
65         toggle.syncState();
66
67         android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
68
69         try {
70             PackageInfo pi = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
71             ver.setText(pi.versionName);
72         } catch (Exception e) {
73             e.printStackTrace();
74         }
75
76         prepare_db();
77         update_account_table();
78         update_accounts(false);
79     }
80
81     @Override
82     protected void onStart() {
83         super.onStart();
84         LinearLayout grp = drawer.findViewById(R.id.nav_actions);
85         for (int i = 0; i < grp.getChildCount(); i++) {
86             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
87                 grp.getChildAt(i).setBackgroundColor(
88                         getResources().getColor(R.color.drawer_background, getTheme()));
89             }
90             else {
91                 grp.getChildAt(i)
92                         .setBackgroundColor(getResources().getColor(R.color.drawer_background));
93             }
94         }
95         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
96             drawer.findViewById(R.id.nav_account_summary).setBackgroundColor(
97                     getResources().getColor(R.color.table_row_even_bg, getTheme()));
98         }
99         else {
100             drawer.findViewById(R.id.nav_account_summary)
101                     .setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
102         }
103     }
104
105     public void fab_new_transaction_clicked(View view) {
106         Intent intent = new Intent(this, NewTransactionActivity.class);
107         startActivity(intent);
108         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
109     }
110
111     public void nav_exit_clicked(View view) {
112         Log.w("mobileledger", "exiting");
113         finish();
114     }
115
116     public void nav_settings_clicked(View view) {
117         Intent intent = new Intent(this, SettingsActivity.class);
118         startActivity(intent);
119     }
120
121     @Override
122     public void onBackPressed() {
123         DrawerLayout drawer = findViewById(R.id.drawer_layout);
124         if (drawer.isDrawerOpen(GravityCompat.START)) {
125             drawer.closeDrawer(GravityCompat.START);
126         } else {
127             super.onBackPressed();
128         }
129     }
130
131     @Override
132     public boolean onCreateOptionsMenu(Menu menu) {
133         // Inflate the menu; this adds items to the action bar if it is present.
134         getMenuInflater().inflate(R.menu.account_summary, menu);
135         mRefresh = menu.findItem(R.id.menu_acc_summary_refresh);
136         if (mRefresh == null) throw new AssertionError();
137
138         mShowHiddenAccounts = menu.findItem(R.id.menu_acc_summary_show_hidden);
139         if (mShowHiddenAccounts == null) throw new AssertionError();
140
141         sBindPreferenceSummaryToValueListener =
142                 new SharedPreferences.OnSharedPreferenceChangeListener() {
143                     @Override
144                     public
145                     void onSharedPreferenceChanged(SharedPreferences preference, String value) {
146                         mShowHiddenAccounts
147                                 .setChecked(preference.getBoolean("show_hidden_accounts", false));
148                     }
149                 };
150         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
151         pref.registerOnSharedPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
152
153         mShowHiddenAccounts.setChecked(pref.getBoolean("show_hidden_accounts", false));
154
155         return true;
156     }
157
158     @Override
159     public boolean onOptionsItemSelected(MenuItem item) {
160         // Handle action bar item clicks here. The action bar will
161         // automatically handle clicks on the Home/Up button, so long
162         // as you specify a parent activity in AndroidManifest.xml.
163 //        int id = item.getItemId();
164
165         //noinspection SimplifiableIfStatement
166         //if (id == R.id.action_settings) {
167         //    return true;
168         // }
169
170         return super.onOptionsItemSelected(item);
171     }
172
173     public void onRefreshAccountSummaryClicked(MenuItem mi) {
174         update_accounts(true);
175     }
176
177     public
178     void onShowHiddenAccountsClicked(MenuItem mi) {
179         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
180         boolean flag = pref.getBoolean("show_hidden_accounts", false);
181
182         SharedPreferences.Editor editor = pref.edit();
183         editor.putBoolean("show_hidden_accounts", !flag);
184         Log.d("pref", "Setting show_hidden_accounts to " + (flag ? "false" : "true"));
185         editor.apply();
186
187         update_account_table();
188     }
189
190     private void prepare_db() {
191         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
192             MobileLedgerDB.setDb_filename(this.getApplicationInfo().deviceProtectedDataDir + "/" + MobileLedgerDB.DATABASE_NAME);
193         }
194         else {
195             MobileLedgerDB.setDb_filename(
196                     this.getApplicationInfo().dataDir + "/" + MobileLedgerDB.DATABASE_NAME);
197         }
198         MobileLedgerDB.initDB(getResources(), getPackageName());
199
200         account_list_last_updated = MobileLedgerDB.get_option_value("last_refresh", (long) 0);
201
202     }
203
204     private void update_accounts(boolean force) {
205         long now = new Date().getTime();
206         if ((now > (account_list_last_updated + (24 * 3600*1000))) || force) {
207             Log.d("db", "accounts last updated at " + account_list_last_updated+" and now is " + now+". re-fetching");
208             update_accounts();
209         }
210     }
211
212     private void update_accounts() {
213         if (mRefresh != null) mRefresh.setVisible(false);
214         Resources rm = getResources();
215
216         ProgressBar pb = findViewById(R.id.progressBar);
217         pb.setVisibility(View.VISIBLE);
218         TextView pt = findViewById(R.id.textProgress);
219         pt.setVisibility(View.VISIBLE);
220         pb.setIndeterminate(true);
221
222         RetrieveAccountsTask task = new RetrieveAccountsTask() {
223             @Override
224             protected void onProgressUpdate(Integer... values) {
225                 if ( values[0] == 0 )
226                     pt.setText(R.string.progress_connecting);
227                 else
228                     pt.setText(String.format(getResources().getString(R.string.progress_N_accounts_loaded), values[0]));
229             }
230
231             @Override
232             protected void onPostExecute(Void result) {
233                 pb.setVisibility(GONE);
234                 pt.setVisibility(GONE);
235                 if (mRefresh != null) mRefresh.setVisible(true);
236                 if (this.error != 0) {
237                     String err_text = rm.getString(this.error);
238                     Log.d("visual", String.format("showing snackbar: %s", err_text));
239                     Snackbar.make(drawer, err_text, Snackbar.LENGTH_LONG ).show();
240                 }
241                 else {
242                     set_option_value("last_refresh", new Date().getTime() );
243                     update_account_table();
244                 }
245             }
246         };
247
248         task.setPref(PreferenceManager.getDefaultSharedPreferences(this));
249         task.execute();
250
251     }
252
253     public int dp2px(float dp) {
254         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
255     }
256
257     Pattern higher_account = Pattern.compile("^[^:]+:");
258
259     private String strip_higher_accounts(String acc_name, int[] count) {
260         count[0] = 0;
261         while (true) {
262             Matcher m = higher_account.matcher(acc_name);
263             if (m.find()) {
264                 count[0]++;
265                 acc_name = m.replaceFirst("");
266             }
267             else break;
268         }
269
270         return acc_name;
271     }
272
273     public void hideAccountClicked(MenuItem item) {
274         db.execSQL("update accounts set hidden=1 where name=?",
275                 new Object[]{clickedAccountRow.getAccountName()});
276         update_account_table();
277     }
278
279     @SuppressLint("DefaultLocale")
280     private void update_account_table() {
281         LinearLayout root = findViewById(R.id.account_root);
282         root.removeAllViewsInLayout();
283
284         View.OnCreateContextMenuListener ccml = new View.OnCreateContextMenuListener() {
285             @Override
286             public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
287                 clickedAccountRow = (AccountRowLayout) v;
288                 getMenuInflater().inflate(R.menu.account_summary_account_menu, menu);
289             }
290         };
291
292         int rowHeight =
293                 (int) (getTheme().obtainStyledAttributes(new int[]{android.R.attr.actionBarSize})
294                         .getDimensionPixelSize(0, dp2px(56)) * 0.75);
295
296         boolean showingHiddenAccounts = PreferenceManager.getDefaultSharedPreferences(this)
297                 .getBoolean("show_hidden_accounts", false);
298         Log.d("pref", "show_hidden_accounts is " + (showingHiddenAccounts ? "true" : "false"));
299
300         try (Cursor cursor = db
301                 .rawQuery("SELECT name, hidden FROM accounts ORDER BY name;", null))
302         {
303             boolean even = false;
304             String skippingAccountName = null;
305             while (cursor.moveToNext()) {
306                 String acc_name = cursor.getString(0);
307                 if (skippingAccountName != null) {
308                     if (acc_name.startsWith(skippingAccountName + ":")) continue;
309
310                     skippingAccountName = null;
311                 }
312
313                 boolean is_hidden = cursor.getInt(1) == 1;
314
315                 if (!showingHiddenAccounts && is_hidden) {
316                     skippingAccountName = acc_name;
317                     continue;
318                 }
319
320                 LinearLayout r = new AccountRowLayout(this, acc_name);
321                 r.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
322                 r.setGravity(Gravity.CENTER_VERTICAL);
323                 r.setPadding(getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(3), getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(4));
324                 r.setMinimumHeight(rowHeight);
325
326                 if (even) {
327                     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
328                         r.setBackgroundColor(
329                                 getResources().getColor(R.color.table_row_even_bg, getTheme()));
330                     }
331                     else {
332                         r.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
333                     }
334                 }
335                 even = !even;
336                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
337                     r.setContextClickable(true);
338                 }
339                 r.setOnCreateContextMenuListener(ccml);
340
341
342                 TextView acc_tv = new TextView(this, null, R.style.account_summary_account_name);
343                 acc_tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 5f));
344                 acc_tv.setGravity(Gravity.CENTER_VERTICAL);
345                 int[] indent_level = new int[]{0};
346                 String short_acc_name = strip_higher_accounts(acc_name, indent_level);
347                 acc_tv.setPadding(indent_level[0] * getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin) / 2, 0, 0, 0);
348                 acc_tv.setText(short_acc_name);
349                 if (is_hidden) acc_tv.setTypeface(null, Typeface.ITALIC);
350                 r.addView(acc_tv);
351
352                 TextView amt_tv = new TextView(this, null, R.style.account_summary_amounts);
353                 amt_tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1f));
354                 amt_tv.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
355                 amt_tv.setGravity(Gravity.CENTER_VERTICAL);
356 //                amt_tv.setGravity(Gravity.CENTER);
357                 amt_tv.setMinWidth(dp2px(60f));
358                 StringBuilder amt_text = new StringBuilder();
359                 try (Cursor cAmounts = db.rawQuery("SELECT currency, value FROM account_values WHERE account = ?", new String[]{acc_name})) {
360                     while (cAmounts.moveToNext()) {
361                         String curr = cAmounts.getString(0);
362                         Float amt = cAmounts.getFloat(1);
363                         if (amt_text.length() != 0) amt_text.append('\n');
364                         amt_text.append(String.format("%s %1.2f", curr, amt));
365                     }
366                 }
367                 amt_tv.setText(amt_text.toString());
368                 if (is_hidden) amt_tv.setTypeface(null, Typeface.ITALIC);
369
370                 r.addView(amt_tv);
371
372                 root.addView(r);
373             }
374         }
375     }
376 }