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