]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
persistent profile list order
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / MobileLedgerProfile.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of Mobile-Ledger.
4  * Mobile-Ledger 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  * Mobile-Ledger 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 Mobile-Ledger. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.model;
19
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.util.Log;
23
24 import net.ktnx.mobileledger.utils.MLDB;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.UUID;
29
30 public final class MobileLedgerProfile {
31     private String uuid;
32     private String name;
33     private String url;
34     private boolean authEnabled;
35     private String authUserName;
36     private String authPassword;
37     public MobileLedgerProfile(String uuid, String name, String url, boolean authEnabled,
38                                String authUserName, String authPassword) {
39         this.uuid = uuid;
40         this.name = name;
41         this.url = url;
42         this.authEnabled = authEnabled;
43         this.authUserName = authUserName;
44         this.authPassword = authPassword;
45     }
46     public MobileLedgerProfile(CharSequence name, CharSequence url, boolean authEnabled,
47                                CharSequence authUserName, CharSequence authPassword) {
48         this.uuid = String.valueOf(UUID.randomUUID());
49         this.name = String.valueOf(name);
50         this.url = String.valueOf(url);
51         this.authEnabled = authEnabled;
52         this.authUserName = String.valueOf(authUserName);
53         this.authPassword = String.valueOf(authPassword);
54     }
55     public static List<MobileLedgerProfile> loadAllFromDB() {
56         List<MobileLedgerProfile> result = new ArrayList<>();
57         SQLiteDatabase db = MLDB.getReadableDatabase();
58         try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
59                                          "auth_password FROM profiles", null))
60         {
61             while (cursor.moveToNext()) {
62                 result.add(new MobileLedgerProfile(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getInt(3) == 1, cursor.getString(4),
63                         cursor.getString(5)));
64             }
65         }
66         return result;
67     }
68     public static void storeProfilesOrder() {
69         SQLiteDatabase db = MLDB.getWritableDatabase();
70         db.beginTransaction();
71         try {
72             int orderNo = 0;
73             for (MobileLedgerProfile p : Data.profiles.getList()) {
74                 db.execSQL("update profiles set order_no=? where uuid=?",
75                         new Object[]{orderNo, p.getUuid()});
76                 orderNo++;
77             }
78             db.setTransactionSuccessful();
79         }
80         finally {
81             db.endTransaction();
82         }
83     }
84     public static List<MobileLedgerProfile> createInitialProfileList() {
85         List<MobileLedgerProfile> result = new ArrayList<>();
86         MobileLedgerProfile first =
87                 new MobileLedgerProfile(UUID.randomUUID().toString(), "default", "", false, "", "");
88         first.storeInDB();
89         result.add(first);
90
91         return result;
92     }
93     public static MobileLedgerProfile loadUUIDFromDB(String profileUUID) {
94         SQLiteDatabase db = MLDB.getReadableDatabase();
95         String name;
96         String url;
97         String authUser;
98         String authPassword;
99         Boolean useAuthentication;
100         try (Cursor cursor = db.rawQuery("SELECT name, url, use_authentication, auth_user, " +
101                                          "auth_password FROM profiles WHERE uuid=?",
102                 new String[]{profileUUID}))
103         {
104             if (cursor.moveToNext()) {
105                 name = cursor.getString(0);
106                 url = cursor.getString(1);
107                 useAuthentication = cursor.getInt(2) == 1;
108                 authUser = useAuthentication ? cursor.getString(3) : null;
109                 authPassword = useAuthentication ? cursor.getString(4) : null;
110             }
111             else {
112                 name = "Unknown profile";
113                 url = "Https://server/url";
114                 useAuthentication = false;
115                 authUser = authPassword = null;
116             }
117         }
118
119         return new MobileLedgerProfile(profileUUID, name, url, useAuthentication, authUser,
120                 authPassword);
121     }
122     public String getUuid() {
123         return uuid;
124     }
125     public String getName() {
126         return name;
127     }
128     public void setName(CharSequence text) {
129         setName(String.valueOf(text));
130     }
131     public void setName(String name) {
132         this.name = name;
133     }
134     public String getUrl() {
135         return url;
136     }
137     public void setUrl(CharSequence text) {
138         setUrl(String.valueOf(text));
139     }
140     public void setUrl(String url) {
141         this.url = url;
142     }
143     public boolean isAuthEnabled() {
144         return authEnabled;
145     }
146     public void setAuthEnabled(boolean authEnabled) {
147         this.authEnabled = authEnabled;
148     }
149     public String getAuthUserName() {
150         return authUserName;
151     }
152     public void setAuthUserName(CharSequence text) {
153         setAuthUserName(String.valueOf(text));
154     }
155     public void setAuthUserName(String authUserName) {
156         this.authUserName = authUserName;
157     }
158     public String getAuthPassword() {
159         return authPassword;
160     }
161     public void setAuthPassword(CharSequence text) {
162         setAuthPassword(String.valueOf(text));
163     }
164     public void setAuthPassword(String authPassword) {
165         this.authPassword = authPassword;
166     }
167     public void storeInDB() {
168         SQLiteDatabase db = MLDB.getWritableDatabase();
169         db.beginTransaction();
170         try {
171             db.execSQL("REPLACE INTO profiles(uuid, name, url, use_authentication, auth_user, " +
172                        "auth_password) VALUES(?, ?, ?, ?, ?, ?)",
173                     new Object[]{uuid, name, url, authEnabled, authEnabled ? authUserName : null,
174                                  authEnabled ? authPassword : null
175                     });
176             db.setTransactionSuccessful();
177         }
178         finally {
179             db.endTransaction();
180         }
181     }
182     public void storeAccount(String name) {
183         SQLiteDatabase db = MLDB.getWritableDatabase();
184
185         do {
186             LedgerAccount acc = new LedgerAccount(name);
187             db.execSQL("replace into accounts(profile, name, name_upper, level, keep) values(?, " +
188                        "?, ?, ?, 1)",
189                     new Object[]{this.uuid, name, name.toUpperCase(), acc.getLevel()});
190             name = acc.getParentName();
191         } while (name != null);
192     }
193     public void storeAccountValue(String name, String currency, Float amount) {
194         SQLiteDatabase db = MLDB.getWritableDatabase();
195         db.execSQL("replace into account_values(profile, account, " +
196                    "currency, value, keep) values(?, ?, ?, ?, 1);",
197                 new Object[]{uuid, name, currency, amount});
198     }
199     public void storeTransaction(LedgerTransaction tr) {
200         SQLiteDatabase db = MLDB.getWritableDatabase();
201         tr.fillDataHash();
202         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
203                 new Object[]{uuid, tr.getId()});
204         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
205                 new Object[]{uuid, tr.getId()});
206
207         db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
208                    "values(?,?,?,?,?,1)",
209                 new Object[]{uuid, tr.getId(), tr.getDate(), tr.getDescription(), tr.getDataHash()
210                 });
211
212         for (LedgerTransactionAccount item : tr.getAccounts()) {
213             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
214                        "account_name, amount, currency) values(?, ?, ?, ?, ?)",
215                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
216                                  item.getCurrency()
217                     });
218         }
219         Log.d("profile", String.format("Transaction %d stored", tr.getId()));
220     }
221     public String get_option_value(String name, String default_value) {
222         SQLiteDatabase db = MLDB.getReadableDatabase();
223         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
224                 new String[]{uuid, name}))
225         {
226             if (cursor.moveToFirst()) {
227                 String result = cursor.getString(0);
228
229                 if (result == null) {
230                     Log.d("profile", "returning default value for " + name);
231                     result = default_value;
232                 }
233                 else Log.d("profile", String.format("option %s=%s", name, result));
234
235                 return result;
236             }
237             else return default_value;
238         }
239         catch (Exception e) {
240             Log.d("db", "returning default value for " + name, e);
241             return default_value;
242         }
243     }
244     public long get_option_value(String name, long default_value) {
245         long longResult;
246         String result = get_option_value(name, "");
247         if ((result == null) || result.isEmpty()) {
248             Log.d("profile", String.format("Returning default value for option %s", name));
249             longResult = default_value;
250         }
251         else {
252             try {
253                 longResult = Long.parseLong(result);
254                 Log.d("profile", String.format("option %s=%s", name, result));
255             }
256             catch (Exception e) {
257                 Log.d("profile", String.format("Returning default value for option %s", name), e);
258                 longResult = default_value;
259             }
260         }
261
262         return longResult;
263     }
264     public void set_option_value(String name, String value) {
265         Log.d("profile", String.format("setting option %s=%s", name, value));
266         SQLiteDatabase db = MLDB.getWritableDatabase();
267         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
268                 new String[]{uuid, name, value});
269     }
270     public void set_option_value(String name, long value) {
271         set_option_value(name, String.valueOf(value));
272     }
273     public void removeFromDB() {
274         SQLiteDatabase db = MLDB.getWritableDatabase();
275         Log.d("db", String.format("removinf progile %s from DB", uuid));
276         db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
277     }
278 }