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