]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/PatternDetailsItem.java
935280519791bb1f2d3be4996f41180ab690e53c
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / PatternDetailsItem.java
1 /*
2  * Copyright © 2021 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.model;
19
20 import android.content.res.Resources;
21
22 import androidx.annotation.NonNull;
23
24 import net.ktnx.mobileledger.R;
25 import net.ktnx.mobileledger.db.PatternAccount;
26 import net.ktnx.mobileledger.db.PatternBase;
27 import net.ktnx.mobileledger.db.PatternHeader;
28 import net.ktnx.mobileledger.utils.Misc;
29
30 import org.jetbrains.annotations.Contract;
31 import org.jetbrains.annotations.NotNull;
32
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35 import java.util.regex.PatternSyntaxException;
36
37 abstract public class PatternDetailsItem {
38     private final Type type;
39     protected Long id;
40     protected Long position;
41
42     protected PatternDetailsItem(Type type) {
43         this.type = type;
44     }
45     @Contract(" -> new")
46     public static @NotNull PatternDetailsItem.Header createHeader() {
47         return new Header();
48     }
49     public static @NotNull PatternDetailsItem.Header createHeader(Header origin) {
50         return new Header(origin);
51     }
52     @Contract("-> new")
53     public static @NotNull PatternDetailsItem.AccountRow createAccountRow() {
54         return new AccountRow();
55     }
56     public static PatternDetailsItem fromRoomObject(PatternBase p) {
57         if (p instanceof PatternHeader) {
58             PatternHeader ph = (PatternHeader) p;
59             Header header = createHeader();
60             header.setId(ph.getId());
61             header.setName(ph.getName());
62             header.setPattern(ph.getRegularExpression());
63             header.setTestText(ph.getTestText());
64
65             if (ph.getTransactionDescriptionMatchGroup() == null)
66                 header.setTransactionDescription(ph.getTransactionDescription());
67             else
68                 header.setTransactionDescriptionMatchGroup(ph.getTransactionDescriptionMatchGroup());
69
70             if (ph.getTransactionCommentMatchGroup() == null)
71                 header.setTransactionComment(ph.getTransactionComment());
72             else
73                 header.setTransactionCommentMatchGroup(ph.getTransactionCommentMatchGroup());
74
75             header.setDateDayMatchGroup(ph.getDateDayMatchGroup());
76             header.setDateMonthMatchGroup(ph.getDateMonthMatchGroup());
77             header.setDateYearMatchGroup(ph.getDateYearMatchGroup());
78
79             return header;
80         }
81         else if (p instanceof PatternAccount) {
82             PatternAccount pa = (PatternAccount) p;
83             AccountRow acc = createAccountRow();
84             acc.setId(pa.getId());
85
86             if (pa.getAccountNameMatchGroup() == null)
87                 acc.setAccountName(Misc.nullIsEmpty(pa.getAccountName()));
88             else
89                 acc.setAccountNameMatchGroup(pa.getAccountNameMatchGroup());
90
91             if (pa.getAccountCommentMatchGroup() == null)
92                 acc.setAccountComment(Misc.nullIsEmpty(pa.getAccountComment()));
93             else
94                 acc.setAccountCommentMatchGroup(pa.getAccountCommentMatchGroup());
95
96             if (pa.getCurrencyMatchGroup() == null) {
97                 final Integer currencyId = pa.getCurrency();
98                 if (currencyId != null && currencyId > 0)
99                     acc.setCurrency(Currency.loadById(currencyId));
100             }
101             else
102                 acc.setCurrencyMatchGroup(pa.getCurrencyMatchGroup());
103
104             final Integer amountMatchGroup = pa.getAmountMatchGroup();
105             if (amountMatchGroup != null && amountMatchGroup > 0)
106                 acc.setAmountMatchGroup(amountMatchGroup);
107             else
108                 acc.setAmount(pa.getAmount());
109
110             return acc;
111         }
112         else {
113             throw new IllegalStateException("Unexpected item class " + p.getClass());
114         }
115     }
116     public Header asHeaderItem() {
117         ensureType(Type.HEADER);
118         return (Header) this;
119     }
120     public AccountRow asAccountRowItem() {
121         ensureType(Type.ACCOUNT_ITEM);
122         return (AccountRow) this;
123     }
124     private void ensureType(Type type) {
125         if (this.type != type)
126             throw new IllegalStateException(
127                     String.format("Type is %s, but %s is required", this.type.toString(),
128                             type.toString()));
129     }
130     void ensureTrue(boolean flag) {
131         if (!flag)
132             throw new IllegalStateException(
133                     "Literal value requested, but it is matched via a pattern group");
134     }
135     void ensureFalse(boolean flag) {
136         if (flag)
137             throw new IllegalStateException("Matching group requested, but the value is a literal");
138     }
139     public long getId() {
140         return id;
141     }
142     public void setId(Long id) {
143         this.id = id;
144     }
145     public void setId(int id) {
146         this.id = (long) id;
147     }
148     public long getPosition() {
149         return position;
150     }
151     public void setPosition(Long position) {
152         this.position = position;
153     }
154     abstract public String getProblem(@NonNull Resources r, int patternGroupCount);
155     public Type getType() {
156         return type;
157     }
158     public enum Type {
159         HEADER(TYPE.header), ACCOUNT_ITEM(TYPE.accountItem);
160         final int index;
161         Type(int i) {
162             index = i;
163         }
164         public int toInt() {
165             return index;
166         }
167     }
168
169     static class PossiblyMatchedValue<T> {
170         private boolean literalValue;
171         private T value;
172         private int matchGroup;
173         public PossiblyMatchedValue() {
174             literalValue = true;
175             value = null;
176         }
177         public PossiblyMatchedValue(@NonNull PossiblyMatchedValue<T> origin) {
178             literalValue = origin.literalValue;
179             value = origin.value;
180             matchGroup = origin.matchGroup;
181         }
182         @NonNull
183         public static PossiblyMatchedValue<Integer> withLiteralInt(Integer initialValue) {
184             PossiblyMatchedValue<Integer> result = new PossiblyMatchedValue<>();
185             result.setValue(initialValue);
186             return result;
187         }
188         @NonNull
189         public static PossiblyMatchedValue<Float> withLiteralFloat(Float initialValue) {
190             PossiblyMatchedValue<Float> result = new PossiblyMatchedValue<>();
191             result.setValue(initialValue);
192             return result;
193         }
194         public static PossiblyMatchedValue<Short> withLiteralShort(Short initialValue) {
195             PossiblyMatchedValue<Short> result = new PossiblyMatchedValue<>();
196             result.setValue(initialValue);
197             return result;
198         }
199         @NonNull
200         public static PossiblyMatchedValue<String> withLiteralString(String initialValue) {
201             PossiblyMatchedValue<String> result = new PossiblyMatchedValue<>();
202             result.setValue(initialValue);
203             return result;
204         }
205         public T getValue() {
206             if (!literalValue)
207                 throw new IllegalStateException("Value is not literal");
208             return value;
209         }
210         public void setValue(T newValue) {
211             value = newValue;
212             literalValue = true;
213         }
214         public boolean hasLiteralValue() {
215             return literalValue;
216         }
217         public int getMatchGroup() {
218             if (literalValue)
219                 throw new IllegalStateException("Value is literal");
220             return matchGroup;
221         }
222         public void setMatchGroup(int group) {
223             this.matchGroup = group;
224             literalValue = false;
225         }
226         public boolean equals(PossiblyMatchedValue<T> other) {
227             if (!other.literalValue == literalValue)
228                 return false;
229             if (literalValue) {
230                 if (value == null)
231                     return other.value == null;
232                 return value.equals(other.value);
233             }
234             else
235                 return matchGroup == other.matchGroup;
236         }
237         public void switchToLiteral() {
238             literalValue = true;
239         }
240     }
241
242     public static class TYPE {
243         public static final int header = 0;
244         public static final int accountItem = 1;
245     }
246
247     public static class AccountRow extends PatternDetailsItem {
248         private final PossiblyMatchedValue<String> accountName =
249                 PossiblyMatchedValue.withLiteralString("");
250         private final PossiblyMatchedValue<String> accountComment =
251                 PossiblyMatchedValue.withLiteralString("");
252         private final PossiblyMatchedValue<Float> amount =
253                 PossiblyMatchedValue.withLiteralFloat(0f);
254         private final PossiblyMatchedValue<Currency> currency = new PossiblyMatchedValue<>();
255         private AccountRow() {
256             super(Type.ACCOUNT_ITEM);
257         }
258         public int getAccountCommentMatchGroup() {
259             return accountComment.getMatchGroup();
260         }
261         public void setAccountCommentMatchGroup(int group) {
262             accountComment.setMatchGroup(group);
263         }
264         public String getAccountComment() {
265             return accountComment.getValue();
266         }
267         public void setAccountComment(String comment) {
268             this.accountComment.setValue(comment);
269         }
270         public int getCurrencyMatchGroup() {
271             return currency.getMatchGroup();
272         }
273         public void setCurrencyMatchGroup(int group) {
274             currency.setMatchGroup(group);
275         }
276         public Currency getCurrency() {
277             return currency.getValue();
278         }
279         public void setCurrency(Currency currency) {
280             this.currency.setValue(currency);
281         }
282         public int getAccountNameMatchGroup() {
283             return accountName.getMatchGroup();
284         }
285         public void setAccountNameMatchGroup(int group) {
286             accountName.setMatchGroup(group);
287         }
288         public String getAccountName() {
289             return accountName.getValue();
290         }
291         public void setAccountName(String accountName) {
292             this.accountName.setValue(accountName);
293         }
294         public boolean hasLiteralAccountName() { return accountName.hasLiteralValue(); }
295         public boolean hasLiteralAmount() {
296             return amount.hasLiteralValue();
297         }
298         public int getAmountMatchGroup() {
299             return amount.getMatchGroup();
300         }
301         public void setAmountMatchGroup(int group) {
302             amount.setMatchGroup(group);
303         }
304         public Float getAmount() {
305             return amount.getValue();
306         }
307         public void setAmount(Float amount) {
308             this.amount.setValue(amount);
309         }
310         public String getProblem(@NonNull Resources r, int patternGroupCount) {
311             if (Misc.emptyIsNull(accountName.getValue()) == null)
312                 return r.getString(R.string.account_name_is_empty);
313             if (!amount.hasLiteralValue() &&
314                 (amount.getMatchGroup() < 1 || amount.getMatchGroup() > patternGroupCount))
315                 return r.getString(R.string.invalid_matching_group_number);
316
317             return null;
318         }
319         public boolean hasLiteralAccountComment() {
320             return accountComment.hasLiteralValue();
321         }
322         public boolean equalContents(AccountRow o) {
323             return amount.equals(o.amount) && accountName.equals(o.accountName) &&
324                    accountComment.equals(o.accountComment);
325         }
326         public void switchToLiteralAmount() {
327             amount.switchToLiteral();
328         }
329         public void switchToLiteralAccountName() {
330             accountName.switchToLiteral();
331         }
332         public void switchToLiteralAccountComment() {
333             accountComment.switchToLiteral();
334         }
335         public PatternAccount toDBO(@NonNull Long patternId) {
336             PatternAccount result = new PatternAccount(id, patternId, position);
337
338             if (accountName.hasLiteralValue())
339                 result.setAccountName(accountName.getValue());
340             else
341                 result.setAccountNameMatchGroup(accountName.getMatchGroup());
342
343             if (accountComment.hasLiteralValue())
344                 result.setAccountComment(accountComment.getValue());
345             else
346                 result.setAccountCommentMatchGroup(accountComment.getMatchGroup());
347
348             if (amount.hasLiteralValue())
349                 result.setAmount(amount.getValue());
350             else
351                 result.setAmountMatchGroup(amount.getMatchGroup());
352
353             return result;
354         }
355     }
356
357     public static class Header extends PatternDetailsItem {
358         private String pattern = "";
359         private String testText = "";
360         private Pattern compiledPattern;
361         private String patternError;
362         private String name = "";
363         private PossiblyMatchedValue<String> transactionDescription =
364                 PossiblyMatchedValue.withLiteralString("");
365         private PossiblyMatchedValue<String> transactionComment =
366                 PossiblyMatchedValue.withLiteralString("");
367         private PossiblyMatchedValue<Integer> dateYear = PossiblyMatchedValue.withLiteralInt(null);
368         private PossiblyMatchedValue<Integer> dateMonth = PossiblyMatchedValue.withLiteralInt(null);
369         private PossiblyMatchedValue<Integer> dateDay = PossiblyMatchedValue.withLiteralInt(null);
370         private Header() {
371             super(Type.HEADER);
372         }
373         public Header(Header origin) {
374             this();
375             id = origin.id;
376             name = origin.name;
377             testText = origin.testText;
378             setPattern(origin.pattern);
379
380             transactionDescription = new PossiblyMatchedValue<>(origin.transactionDescription);
381             transactionComment = new PossiblyMatchedValue<>(origin.transactionComment);
382
383             dateYear = new PossiblyMatchedValue<>(origin.dateYear);
384             dateMonth = new PossiblyMatchedValue<>(origin.dateMonth);
385             dateDay = new PossiblyMatchedValue<>(origin.dateDay);
386         }
387         public String getName() {
388             return name;
389         }
390         public void setName(String name) {
391             this.name = name;
392         }
393         public String getPattern() {
394             return pattern;
395         }
396         public void setPattern(String pattern) {
397             this.pattern = pattern;
398             if (pattern != null) {
399                 try {
400                     this.compiledPattern = Pattern.compile(pattern);
401                     this.patternError = null;
402                 }
403                 catch (PatternSyntaxException e) {
404                     this.compiledPattern = null;
405                     this.patternError = e.getMessage();
406                 }
407             }
408             else {
409                 patternError = "Missing pattern";
410             }
411         }
412         @NonNull
413         @Override
414         public String toString() {
415             return super.toString() +
416                    String.format(" name[%s] pat[%s] test[%s]", name, pattern, testText);
417         }
418         public String getTestText() {
419             return testText;
420         }
421         public void setTestText(String testText) {
422             this.testText = testText;
423         }
424         public String getTransactionDescription() {
425             return transactionDescription.getValue();
426         }
427         public void setTransactionDescription(String transactionDescription) {
428             this.transactionDescription.setValue(transactionDescription);
429         }
430         public String getTransactionComment() {
431             return transactionComment.getValue();
432         }
433         public void setTransactionComment(String transactionComment) {
434             this.transactionComment.setValue(transactionComment);
435         }
436         public Integer getDateYear() {
437             return dateYear.getValue();
438         }
439         public void setDateYear(Integer dateYear) {
440             this.dateYear.setValue(dateYear);
441         }
442         public Integer getDateMonth() {
443             return dateMonth.getValue();
444         }
445         public void setDateMonth(Integer dateMonth) {
446             this.dateMonth.setValue(dateMonth);
447         }
448         public Integer getDateDay() {
449             return dateDay.getValue();
450         }
451         public void setDateDay(Integer dateDay) {
452             this.dateDay.setValue(dateDay);
453         }
454         public int getDateYearMatchGroup() {
455             return dateYear.getMatchGroup();
456         }
457         public void setDateYearMatchGroup(int dateYearMatchGroup) {
458             this.dateYear.setMatchGroup(dateYearMatchGroup);
459         }
460         public int getDateMonthMatchGroup() {
461             return dateMonth.getMatchGroup();
462         }
463         public void setDateMonthMatchGroup(int dateMonthMatchGroup) {
464             this.dateMonth.setMatchGroup(dateMonthMatchGroup);
465         }
466         public int getDateDayMatchGroup() {
467             return dateDay.getMatchGroup();
468         }
469         public void setDateDayMatchGroup(int dateDayMatchGroup) {
470             this.dateDay.setMatchGroup(dateDayMatchGroup);
471         }
472         public boolean hasLiteralDateYear() {
473             return dateYear.hasLiteralValue();
474         }
475         public boolean hasLiteralDateMonth() {
476             return dateMonth.hasLiteralValue();
477         }
478         public boolean hasLiteralDateDay() {
479             return dateDay.hasLiteralValue();
480         }
481         public boolean hasLiteralTransactionDescription() { return transactionDescription.hasLiteralValue(); }
482         public boolean hasLiteralTransactionComment() { return transactionComment.hasLiteralValue(); }
483         public String getProblem(@NonNull Resources r, int patternGroupCount) {
484             if (patternError != null)
485                 return r.getString(R.string.pattern_has_errors) + ": " + patternError;
486             if (Misc.emptyIsNull(pattern) == null)
487                 return r.getString(R.string.pattern_is_empty);
488
489             if (!dateYear.hasLiteralValue() && compiledPattern != null &&
490                 (dateDay.getMatchGroup() < 1 || dateDay.getMatchGroup() > patternGroupCount))
491                 return r.getString(R.string.invalid_matching_group_number);
492
493             if (!dateMonth.hasLiteralValue() && compiledPattern != null &&
494                 (dateMonth.getMatchGroup() < 1 || dateMonth.getMatchGroup() > patternGroupCount))
495                 return r.getString(R.string.invalid_matching_group_number);
496
497             if (!dateDay.hasLiteralValue() && compiledPattern != null &&
498                 (dateDay.getMatchGroup() < 1 || dateDay.getMatchGroup() > patternGroupCount))
499                 return r.getString(R.string.invalid_matching_group_number);
500
501             return null;
502         }
503
504         public boolean equalContents(Header o) {
505             if (!dateDay.equals(o.dateDay))
506                 return false;
507             if (!dateMonth.equals(o.dateMonth))
508                 return false;
509             if (!dateYear.equals(o.dateYear))
510                 return false;
511             if (!transactionDescription.equals(o.transactionDescription))
512                 return false;
513             if (!transactionComment.equals(o.transactionComment))
514                 return true;
515
516             return Misc.equalStrings(name, o.name) && Misc.equalStrings(pattern, o.pattern) &&
517                    Misc.equalStrings(testText, o.testText);
518         }
519         public String getMatchGroupText(int group) {
520             if (compiledPattern != null && testText != null) {
521                 Matcher m = compiledPattern.matcher(testText);
522                 if (m.matches())
523                     return m.group(group);
524             }
525
526             return "ø";
527         }
528         public Pattern getCompiledPattern() {
529             return compiledPattern;
530         }
531         public void switchToLiteralTransactionDescription() {
532             transactionDescription.switchToLiteral();
533         }
534         public void switchToLiteralTransactionComment() {
535             transactionComment.switchToLiteral();
536         }
537         public int getTransactionDescriptionMatchGroup() {
538             return transactionDescription.getMatchGroup();
539         }
540         public void setTransactionDescriptionMatchGroup(int group) {
541             transactionDescription.setMatchGroup(group);
542         }
543         public int getTransactionCommentMatchGroup() {
544             return transactionComment.getMatchGroup();
545         }
546         public void setTransactionCommentMatchGroup(int group) {
547             transactionComment.setMatchGroup(group);
548         }
549         public void switchToLiteralDateYear() {
550             dateYear.switchToLiteral();
551         }
552         public void switchToLiteralDateMonth() {
553             dateMonth.switchToLiteral();
554         }
555         public void switchToLiteralDateDay() { dateDay.switchToLiteral(); }
556         public PatternHeader toDBO() {
557             PatternHeader result = new PatternHeader(id, name, pattern);
558
559             if (Misc.emptyIsNull(testText) != null)
560                 result.setTestText(testText);
561
562             if (transactionDescription.hasLiteralValue())
563                 result.setTransactionDescription(transactionDescription.getValue());
564             else
565                 result.setTransactionDescriptionMatchGroup(transactionDescription.getMatchGroup());
566
567             if (transactionComment.hasLiteralValue())
568                 result.setTransactionComment(transactionComment.getValue());
569             else
570                 result.setTransactionCommentMatchGroup(transactionComment.getMatchGroup());
571
572             if (dateYear.hasLiteralValue())
573                 result.setDateYear(dateYear.getValue());
574             else
575                 result.setDateYearMatchGroup(dateYear.getMatchGroup());
576
577             if (dateMonth.hasLiteralValue())
578                 result.setDateMonth(dateMonth.getValue());
579             else
580                 result.setDateMonthMatchGroup(dateMonth.getMatchGroup());
581
582             if (dateDay.hasLiteralValue())
583                 result.setDateDay(dateDay.getValue());
584             else
585                 result.setDateDayMatchGroup(dateDay.getMatchGroup());
586
587             return result;
588         }
589     }
590 }