]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java
whitespace
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / utils / MLDB.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.utils;
19
20 import android.annotation.TargetApi;
21 import android.content.Context;
22 import android.database.Cursor;
23 import android.database.MatrixCursor;
24 import android.database.sqlite.SQLiteDatabase;
25 import android.os.AsyncTask;
26 import android.os.Build;
27 import android.provider.FontsContract;
28 import android.widget.AutoCompleteTextView;
29 import android.widget.FilterQueryProvider;
30 import android.widget.SimpleCursorAdapter;
31
32 import net.ktnx.mobileledger.App;
33 import net.ktnx.mobileledger.async.DbOpQueue;
34 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
35 import net.ktnx.mobileledger.model.Data;
36 import net.ktnx.mobileledger.model.MobileLedgerProfile;
37
38 import org.jetbrains.annotations.NonNls;
39
40 import java.util.Locale;
41
42 import static net.ktnx.mobileledger.utils.Logger.debug;
43
44 public final class MLDB {
45     public static final String ACCOUNTS_TABLE = "accounts";
46     public static final String DESCRIPTION_HISTORY_TABLE = "description_history";
47     public static final String OPT_LAST_SCRAPE = "last_scrape";
48     @NonNls
49     public static final String OPT_PROFILE_UUID = "profile_uuid";
50     private static final String NO_PROFILE = "-";
51     @SuppressWarnings("unused")
52     static public int getIntOption(String name, int default_value) {
53         String s = getOption(name, String.valueOf(default_value));
54         try {
55             return Integer.parseInt(s);
56         }
57         catch (Exception e) {
58             debug("db", "returning default int value of " + name, e);
59             return default_value;
60         }
61     }
62     @SuppressWarnings("unused")
63     static public long getLongOption(String name, long default_value) {
64         String s = getOption(name, String.valueOf(default_value));
65         try {
66             return Long.parseLong(s);
67         }
68         catch (Exception e) {
69             debug("db", "returning default long value of " + name, e);
70             return default_value;
71         }
72     }
73     static public void getOption(String name, String defaultValue, GetOptCallback cb) {
74         AsyncTask<Void, Void, String> t = new AsyncTask<Void, Void, String>() {
75             @Override
76             protected String doInBackground(Void... params) {
77                 SQLiteDatabase db = App.getDatabase();
78                 try (Cursor cursor = db
79                         .rawQuery("select value from options where profile = ? and name=?",
80                                 new String[]{NO_PROFILE, name}))
81                 {
82                     if (cursor.moveToFirst()) {
83                         String result = cursor.getString(0);
84
85                         if (result == null) result = defaultValue;
86
87                         debug("async-db", "option " + name + "=" + result);
88                         return result;
89                     }
90                     else return defaultValue;
91                 }
92                 catch (Exception e) {
93                     debug("db", "returning default value for " + name, e);
94                     return defaultValue;
95                 }
96             }
97             @Override
98             protected void onPostExecute(String result) {
99                 cb.onResult(result);
100             }
101         };
102
103         t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
104     }
105     static public String getOption(String name, String default_value) {
106         debug("db", "about to fetch option " + name);
107         SQLiteDatabase db = App.getDatabase();
108         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
109                 new String[]{NO_PROFILE, name}))
110         {
111             if (cursor.moveToFirst()) {
112                 String result = cursor.getString(0);
113
114                 if (result == null) result = default_value;
115
116                 debug("db", "option " + name + "=" + result);
117                 return result;
118             }
119             else return default_value;
120         }
121         catch (Exception e) {
122             debug("db", "returning default value for " + name, e);
123             return default_value;
124         }
125     }
126     static public void setOption(String name, String value) {
127         debug("option", String.format("%s := %s", name, value));
128         DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
129                 new String[]{NO_PROFILE, name, value});
130     }
131     @SuppressWarnings("unused")
132     static public void setLongOption(String name, long value) {
133         setOption(name, String.valueOf(value));
134     }
135     @TargetApi(Build.VERSION_CODES.N)
136     public static void hookAutocompletionAdapter(final Context context,
137                                                  final AutoCompleteTextView view,
138                                                  final String table, final String field) {
139         hookAutocompletionAdapter(context, view, table, field, true, null, null);
140     }
141     @TargetApi(Build.VERSION_CODES.N)
142     public static void hookAutocompletionAdapter(final Context context,
143                                                  final AutoCompleteTextView view,
144                                                  final String table, final String field,
145                                                  final boolean profileSpecific,
146                                                  final DescriptionSelectedCallback callback,
147                                                  final MobileLedgerProfile profile) {
148         String[] from = {field};
149         int[] to = {android.R.id.text1};
150         SimpleCursorAdapter adapter =
151                 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
152                         from, to, 0);
153         adapter.setStringConversionColumn(1);
154
155         FilterQueryProvider provider = constraint -> {
156             if (constraint == null) return null;
157
158             String str = constraint.toString().toUpperCase();
159             debug("autocompletion", "Looking for " + str);
160             String[] col_names = {FontsContract.Columns._ID, field};
161             MatrixCursor c = new MatrixCursor(col_names);
162
163             String sql;
164             String[] params;
165             if (profileSpecific) {
166                 MobileLedgerProfile p = (profile == null) ? Data.profile.getValue() : profile;
167                 if (p == null) throw new AssertionError();
168                 sql = String.format("SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
169                                     "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
170                                     "WHEN %s_upper LIKE '%% '||?||'%%' then 3 else 9 end " +
171                                     "FROM %s " +
172                                     "WHERE profile=? AND %s_upper LIKE '%%'||?||'%%' " +
173                                     "ORDER BY 2, 1;", field, field, field, field, table, field);
174                 params = new String[]{str, str, str, p.getUuid(), str};
175             }
176             else {
177                 sql = String.format("SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
178                                     "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
179                                     "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
180                                     "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
181                                     "ORDER BY 2, 1;", field, field, field, field, table, field);
182                 params = new String[]{str, str, str, str};
183             }
184             debug("autocompletion", sql);
185             SQLiteDatabase db = App.getDatabase();
186
187             try (Cursor matches = db.rawQuery(sql, params)) {
188                 int i = 0;
189                 while (matches.moveToNext()) {
190                     String match = matches.getString(0);
191                     int order = matches.getInt(1);
192                     debug("autocompletion",
193                             String.format(Locale.ENGLISH, "match: %s |%d", match, order));
194                     c.newRow().add(i++).add(match);
195                 }
196             }
197
198             return c;
199
200         };
201
202         adapter.setFilterQueryProvider(provider);
203
204         view.setAdapter(adapter);
205
206         if (callback != null) view.setOnItemClickListener((parent, itemView, position, id) -> {
207             callback.descriptionSelected(String.valueOf(view.getText()));
208         });
209     }
210 }
211