]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/AccountSummary.java
show plain account names in the summary and indent the sub-accounts
[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.pm.PackageInfo;
6 import android.content.res.Resources;
7 import android.database.Cursor;
8 import android.os.Build;
9 import android.os.Bundle;
10 import android.preference.PreferenceManager;
11 import android.support.design.widget.Snackbar;
12 import android.support.v4.view.GravityCompat;
13 import android.support.v4.widget.DrawerLayout;
14 import android.support.v7.app.ActionBarDrawerToggle;
15 import android.support.v7.app.AppCompatActivity;
16 import android.support.v7.widget.Toolbar;
17 import android.util.Log;
18 import android.util.TypedValue;
19 import android.view.Gravity;
20 import android.view.Menu;
21 import android.view.MenuItem;
22 import android.view.View;
23 import android.view.ViewGroup;
24 import android.widget.EditText;
25 import android.widget.LinearLayout;
26 import android.widget.ProgressBar;
27 import android.widget.TableLayout;
28 import android.widget.TableRow;
29 import android.widget.TextView;
30
31 import java.util.Date;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34
35 import static android.view.View.GONE;
36 import static net.ktnx.mobileledger.MobileLedgerDB.db;
37 import static net.ktnx.mobileledger.MobileLedgerDB.set_option_value;
38
39 public class AccountSummary extends AppCompatActivity {
40     DrawerLayout drawer;
41
42     private static long account_list_last_updated;
43     private static boolean account_list_needs_update = true;
44     public static void preferences_changed() {
45         account_list_needs_update = true;
46     }
47     MenuItem mRefresh;
48
49     @Override
50     protected void onCreate(Bundle savedInstanceState) {
51         super.onCreate(savedInstanceState);
52         setContentView(R.layout.activity_account_summary);
53         Toolbar toolbar = findViewById(R.id.toolbar);
54         setSupportActionBar(toolbar);
55
56         drawer = findViewById(R.id.drawer_layout);
57         ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
58                 this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
59         drawer.addDrawerListener(toggle);
60         toggle.syncState();
61
62         android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
63
64         try {
65             PackageInfo pi = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
66             ver.setText(pi.versionName);
67         } catch (Exception e) {
68             e.printStackTrace();
69         }
70
71         prepare_db();
72         update_account_table();
73         update_accounts(false);
74     }
75
76     public void fab_new_transaction_clicked(View view) {
77         Intent intent = new Intent(this, NewTransactionActivity.class);
78         startActivity(intent);
79     }
80
81     public void nav_exit_clicked(View view) {
82         Log.w("mobileledger", "exiting");
83         finish();
84     }
85
86     public void nav_settings_clicked(View view) {
87         Intent intent = new Intent(this, SettingsActivity.class);
88         startActivity(intent);
89     }
90
91     @Override
92     public void onBackPressed() {
93         DrawerLayout drawer = findViewById(R.id.drawer_layout);
94         if (drawer.isDrawerOpen(GravityCompat.START)) {
95             drawer.closeDrawer(GravityCompat.START);
96         } else {
97             super.onBackPressed();
98         }
99     }
100
101     @Override
102     public boolean onCreateOptionsMenu(Menu menu) {
103         // Inflate the menu; this adds items to the action bar if it is present.
104         getMenuInflater().inflate(R.menu.account_summary, menu);
105         mRefresh = menu.findItem(R.id.menu_acc_summary_refresh);
106         assert mRefresh != null;
107         return true;
108     }
109
110     @Override
111     public boolean onOptionsItemSelected(MenuItem item) {
112         // Handle action bar item clicks here. The action bar will
113         // automatically handle clicks on the Home/Up button, so long
114         // as you specify a parent activity in AndroidManifest.xml.
115         int id = item.getItemId();
116
117         //noinspection SimplifiableIfStatement
118         //if (id == R.id.action_settings) {
119         //    return true;
120         // }
121
122         return super.onOptionsItemSelected(item);
123     }
124
125     public void onRefreshAccountSummaryClicked(MenuItem mi) {
126         update_accounts(true);
127     }
128
129     private void prepare_db() {
130         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
131             MobileLedgerDB.setDb_filename(this.getApplicationInfo().deviceProtectedDataDir + "/" + MobileLedgerDB.DATABASE_NAME);
132         }
133         else {
134             MobileLedgerDB.setDb_filename(MobileLedgerDB.DATABASE_NAME);
135         }
136         MobileLedgerDB.initDB();
137
138         MobileLedgerDB.applyRevisions(getResources(), getPackageName());
139
140         account_list_last_updated = MobileLedgerDB.get_option_value("last_refresh", (long) 0);
141
142     }
143
144     private void update_accounts(boolean force) {
145         long now = new Date().getTime();
146         if ((now > (account_list_last_updated + (24 * 3600*1000))) || force) {
147             Log.d("db", "accounts last updated at " + account_list_last_updated+" and now is " + now+". re-fetching");
148             update_accounts();
149         }
150     }
151
152     private void update_accounts() {
153         mRefresh.setVisible(false);
154         Resources rm = getResources();
155
156         ProgressBar pb = findViewById(R.id.progressBar);
157         pb.setVisibility(View.VISIBLE);
158         TextView pt = findViewById(R.id.textProgress);
159         pt.setVisibility(View.VISIBLE);
160         pb.setIndeterminate(true);
161
162         RetrieveAccountsTask task = new RetrieveAccountsTask() {
163             @Override
164             protected void onProgressUpdate(Integer... values) {
165                 if ( values[0] == 0 )
166                     pt.setText(R.string.progress_connecting);
167                 else
168                     pt.setText(String.format(getResources().getString(R.string.progress_N_accounts_loaded), values[0]));
169             }
170
171             @Override
172             protected void onPostExecute(Void result) {
173                 pb.setVisibility(GONE);
174                 pt.setVisibility(GONE);
175                 mRefresh.setVisible(true);
176                 if (this.error != 0) {
177                     String err_text = rm.getString(this.error);
178                     Log.d("visual", String.format("showing snackbar: %s", err_text));
179                     Snackbar.make(drawer, err_text, Snackbar.LENGTH_LONG ).show();
180                 }
181                 else {
182                     set_option_value("last_refresh", new Date().getTime() );
183                     update_account_table();
184                 }
185             }
186         };
187
188         task.setPref(PreferenceManager.getDefaultSharedPreferences(this));
189         task.execute();
190
191     }
192
193     public int dp2px(float dp) {
194         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
195     }
196
197     Pattern higher_account = Pattern.compile("^[^:]+:");
198
199     private String strip_higher_accounts(String acc_name, int[] count) {
200         count[0] = 0;
201         while (true) {
202             Matcher m = higher_account.matcher(acc_name);
203             if (m.find()) {
204                 count[0]++;
205                 acc_name = m.replaceFirst("");
206             }
207             else break;
208         }
209
210         return acc_name;
211     }
212
213     @SuppressLint("DefaultLocale")
214     private void update_account_table() {
215         LinearLayout root = findViewById(R.id.account_root);
216         root.removeAllViewsInLayout();
217
218
219         try (Cursor cursor = db.rawQuery("SELECT name FROM accounts ORDER BY name;", null)) {
220             boolean even = false;
221             while (cursor.moveToNext()) {
222                 String acc_name = cursor.getString(0);
223
224                 TableLayout t = new TableLayout(this);
225                 TableRow r = new TableRow(this);
226                 r.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
227                 r.setGravity(Gravity.CENTER_VERTICAL);
228                 r.setPadding(getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(2), getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(4));
229                 if (even)
230                     r.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
231                 even = !even;
232
233                 TextView acc_tv = new TextView(this, null, R.style.account_summary_account_name);
234                 acc_tv.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 9f));
235                 int[] indent_level = new int[]{0};
236                 String short_acc_name = strip_higher_accounts(acc_name, indent_level);
237                 acc_tv.setPadding(indent_level[0] * getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin) / 2, 0, 0, 0);
238                 acc_tv.setText(short_acc_name);
239                 r.addView(acc_tv);
240
241                 TextView amt_tv = new TextView(this, null, R.style.account_summary_amounts);
242                 amt_tv.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
243                 amt_tv.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
244                 amt_tv.setGravity(Gravity.CENTER);
245                 amt_tv.setMinWidth(dp2px(40f));
246                 StringBuilder amt_text = new StringBuilder();
247                 try (Cursor cAmounts = db.rawQuery("SELECT currency, value FROM account_values WHERE account = ?", new String[]{acc_name})) {
248                     while (cAmounts.moveToNext()) {
249                         String curr = cAmounts.getString(0);
250                         Float amt = cAmounts.getFloat(1);
251                         if (amt_text.length() != 0) amt_text.append('\n');
252                         amt_text.append(String.format("%s %1.2f", curr, amt));
253                     }
254                 }
255                 amt_tv.setText(amt_text.toString());
256
257                 r.addView(amt_tv);
258
259                 t.addView(r);
260
261                 root.addView(t);
262             }
263         }
264     }
265 }