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