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