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.
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.
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/>.
18 package net.ktnx.mobileledger.model;
20 import android.content.res.Resources;
21 import android.graphics.Color;
22 import android.graphics.Typeface;
23 import android.text.SpannableString;
24 import android.text.Spanned;
25 import android.text.style.ForegroundColorSpan;
26 import android.text.style.StyleSpan;
27 import android.text.style.UnderlineSpan;
29 import androidx.annotation.NonNull;
31 import net.ktnx.mobileledger.R;
32 import net.ktnx.mobileledger.db.TemplateAccount;
33 import net.ktnx.mobileledger.db.TemplateBase;
34 import net.ktnx.mobileledger.db.TemplateHeader;
35 import net.ktnx.mobileledger.utils.Logger;
36 import net.ktnx.mobileledger.utils.Misc;
38 import org.jetbrains.annotations.Contract;
39 import org.jetbrains.annotations.NotNull;
41 import java.util.Locale;
42 import java.util.Objects;
43 import java.util.regex.Matcher;
44 import java.util.regex.Pattern;
45 import java.util.regex.PatternSyntaxException;
47 abstract public class TemplateDetailsItem {
48 private final Type type;
50 protected long position;
52 protected TemplateDetailsItem(Type type) {
56 public static @NotNull TemplateDetailsItem.Header createHeader() {
59 public static @NotNull TemplateDetailsItem.Header createHeader(Header origin) {
60 return new Header(origin);
63 public static @NotNull TemplateDetailsItem.AccountRow createAccountRow() {
64 return new AccountRow();
66 public static TemplateDetailsItem fromRoomObject(TemplateBase p) {
67 if (p instanceof TemplateHeader) {
68 TemplateHeader ph = (TemplateHeader) p;
69 Header header = createHeader();
70 header.setId(ph.getId());
71 header.setName(ph.getName());
72 header.setPattern(ph.getRegularExpression());
73 header.setTestText(ph.getTestText());
75 if (ph.getTransactionDescriptionMatchGroup() == null)
76 header.setTransactionDescription(ph.getTransactionDescription());
78 header.setTransactionDescriptionMatchGroup(
79 ph.getTransactionDescriptionMatchGroup());
81 if (ph.getTransactionCommentMatchGroup() == null)
82 header.setTransactionComment(ph.getTransactionComment());
84 header.setTransactionCommentMatchGroup(ph.getTransactionCommentMatchGroup());
86 if (ph.getDateDayMatchGroup() == null)
87 header.setDateDay(ph.getDateDay());
89 header.setDateDayMatchGroup(ph.getDateDayMatchGroup());
91 if (ph.getDateMonthMatchGroup() == null)
92 header.setDateMonth(ph.getDateMonth());
94 header.setDateMonthMatchGroup(ph.getDateMonthMatchGroup());
96 if (ph.getDateYearMatchGroup() == null)
97 header.setDateYear(ph.getDateYear());
99 header.setDateYearMatchGroup(ph.getDateYearMatchGroup());
101 header.setFallback(ph.isFallback());
105 else if (p instanceof TemplateAccount) {
106 TemplateAccount pa = (TemplateAccount) p;
107 AccountRow acc = createAccountRow();
108 acc.setId(pa.getId());
109 acc.setPosition(pa.getPosition());
111 if (pa.getAccountNameMatchGroup() == null)
112 acc.setAccountName(Misc.nullIsEmpty(pa.getAccountName()));
114 acc.setAccountNameMatchGroup(pa.getAccountNameMatchGroup());
116 if (pa.getAccountCommentMatchGroup() == null)
117 acc.setAccountComment(Misc.nullIsEmpty(pa.getAccountComment()));
119 acc.setAccountCommentMatchGroup(pa.getAccountCommentMatchGroup());
121 if (pa.getCurrencyMatchGroup() == null) {
122 final Integer currencyId = pa.getCurrency();
123 if (currencyId != null && currencyId > 0)
124 acc.setCurrency(Currency.loadById(currencyId));
127 acc.setCurrencyMatchGroup(pa.getCurrencyMatchGroup());
129 final Integer amountMatchGroup = pa.getAmountMatchGroup();
130 if (amountMatchGroup != null && amountMatchGroup > 0) {
131 acc.setAmountMatchGroup(amountMatchGroup);
132 final Boolean negateAmount = pa.getNegateAmount();
133 acc.setNegateAmount(negateAmount != null && negateAmount);
136 acc.setAmount(pa.getAmount());
141 throw new IllegalStateException("Unexpected item class " + p.getClass());
144 public Header asHeaderItem() {
145 ensureType(Type.HEADER);
146 return (Header) this;
148 public AccountRow asAccountRowItem() {
149 ensureType(Type.ACCOUNT_ITEM);
150 return (AccountRow) this;
152 private void ensureType(Type type) {
153 if (this.type != type)
154 throw new IllegalStateException(
155 String.format("Type is %s, but %s is required", this.type.toString(),
158 void ensureTrue(boolean flag) {
160 throw new IllegalStateException(
161 "Literal value requested, but it is matched via a pattern group");
163 void ensureFalse(boolean flag) {
165 throw new IllegalStateException("Matching group requested, but the value is a literal");
167 public long getId() {
170 public void setId(Long id) {
173 public void setId(int id) {
176 public long getPosition() {
179 public void setPosition(long position) {
180 this.position = position;
182 abstract public String getProblem(@NonNull Resources r, int patternGroupCount);
183 public Type getType() {
187 HEADER(TYPE.header), ACCOUNT_ITEM(TYPE.accountItem);
197 static class PossiblyMatchedValue<T> {
198 private boolean literalValue;
200 private int matchGroup;
201 public PossiblyMatchedValue() {
205 public PossiblyMatchedValue(@NonNull PossiblyMatchedValue<T> origin) {
206 literalValue = origin.literalValue;
207 value = origin.value;
208 matchGroup = origin.matchGroup;
211 public static PossiblyMatchedValue<Integer> withLiteralInt(Integer initialValue) {
212 PossiblyMatchedValue<Integer> result = new PossiblyMatchedValue<>();
213 result.setValue(initialValue);
217 public static PossiblyMatchedValue<Float> withLiteralFloat(Float initialValue) {
218 PossiblyMatchedValue<Float> result = new PossiblyMatchedValue<>();
219 result.setValue(initialValue);
222 public static PossiblyMatchedValue<Short> withLiteralShort(Short initialValue) {
223 PossiblyMatchedValue<Short> result = new PossiblyMatchedValue<>();
224 result.setValue(initialValue);
228 public static PossiblyMatchedValue<String> withLiteralString(String initialValue) {
229 PossiblyMatchedValue<String> result = new PossiblyMatchedValue<>();
230 result.setValue(initialValue);
233 public void copyFrom(@NonNull PossiblyMatchedValue<T> origin) {
234 literalValue = origin.literalValue;
235 value = origin.value;
236 matchGroup = origin.matchGroup;
238 public T getValue() {
240 throw new IllegalStateException("Value is not literal");
243 public void setValue(T newValue) {
247 public boolean hasLiteralValue() {
250 public int getMatchGroup() {
252 throw new IllegalStateException("Value is literal");
255 public void setMatchGroup(int group) {
256 this.matchGroup = group;
257 literalValue = false;
259 public boolean equals(PossiblyMatchedValue<T> other) {
260 if (!other.literalValue == literalValue)
264 return other.value == null;
265 return value.equals(other.value);
268 return matchGroup == other.matchGroup;
270 public void switchToLiteral() {
273 public String toString() {
278 return value.toString();
280 return "grp:" + matchGroup;
283 public boolean isEmpty() {
285 return value == null || Misc.emptyIsNull(value.toString()) == null;
287 return matchGroup > 0;
291 public static class TYPE {
292 public static final int header = 0;
293 public static final int accountItem = 1;
296 public static class AccountRow extends TemplateDetailsItem {
297 private final PossiblyMatchedValue<String> accountName =
298 PossiblyMatchedValue.withLiteralString("");
299 private final PossiblyMatchedValue<String> accountComment =
300 PossiblyMatchedValue.withLiteralString("");
301 private final PossiblyMatchedValue<Float> amount =
302 PossiblyMatchedValue.withLiteralFloat(null);
303 private final PossiblyMatchedValue<Currency> currency = new PossiblyMatchedValue<>();
304 private boolean negateAmount;
305 public AccountRow() {
306 super(Type.ACCOUNT_ITEM);
308 public AccountRow(AccountRow origin) {
309 super(Type.ACCOUNT_ITEM);
311 position = origin.position;
312 accountName.copyFrom(origin.accountName);
313 accountComment.copyFrom(origin.accountComment);
314 amount.copyFrom(origin.amount);
315 currency.copyFrom(origin.currency);
316 negateAmount = origin.negateAmount;
318 public boolean isNegateAmount() {
321 public void setNegateAmount(boolean negateAmount) {
322 this.negateAmount = negateAmount;
324 public int getAccountCommentMatchGroup() {
325 return accountComment.getMatchGroup();
327 public void setAccountCommentMatchGroup(int group) {
328 accountComment.setMatchGroup(group);
330 public String getAccountComment() {
331 return accountComment.getValue();
333 public void setAccountComment(String comment) {
334 this.accountComment.setValue(comment);
336 public int getCurrencyMatchGroup() {
337 return currency.getMatchGroup();
339 public void setCurrencyMatchGroup(int group) {
340 currency.setMatchGroup(group);
342 public Currency getCurrency() {
343 return currency.getValue();
345 public void setCurrency(Currency currency) {
346 this.currency.setValue(currency);
348 public int getAccountNameMatchGroup() {
349 return accountName.getMatchGroup();
351 public void setAccountNameMatchGroup(int group) {
352 accountName.setMatchGroup(group);
354 public String getAccountName() {
355 return accountName.getValue();
357 public void setAccountName(String accountName) {
358 this.accountName.setValue(accountName);
360 public boolean hasLiteralAccountName() { return accountName.hasLiteralValue(); }
361 public boolean hasLiteralAmount() {
362 return amount.hasLiteralValue();
364 public int getAmountMatchGroup() {
365 return amount.getMatchGroup();
367 public void setAmountMatchGroup(int group) {
368 amount.setMatchGroup(group);
370 public Float getAmount() {
371 return amount.getValue();
373 public void setAmount(Float amount) {
374 this.amount.setValue(amount);
376 public String getProblem(@NonNull Resources r, int patternGroupCount) {
377 if (Misc.emptyIsNull(accountName.getValue()) == null)
378 return r.getString(R.string.account_name_is_empty);
379 if (!amount.hasLiteralValue() &&
380 (amount.getMatchGroup() < 1 || amount.getMatchGroup() > patternGroupCount))
381 return r.getString(R.string.invalid_matching_group_number);
385 public boolean hasLiteralAccountComment() {
386 return accountComment.hasLiteralValue();
388 public boolean equalContents(AccountRow o) {
389 if (position != o.position) {
390 Logger.debug("cmpAcc",
391 String.format(Locale.US, "[%d] != [%d]: pos %d != pos %d", getId(),
392 o.getId(), position, o.position));
395 return amount.equals(o.amount) && accountName.equals(o.accountName) &&
396 position == o.position && accountComment.equals(o.accountComment) &&
397 negateAmount == o.negateAmount;
399 public void switchToLiteralAmount() {
400 amount.switchToLiteral();
402 public void switchToLiteralAccountName() {
403 accountName.switchToLiteral();
405 public void switchToLiteralAccountComment() {
406 accountComment.switchToLiteral();
408 public TemplateAccount toDBO(@NonNull Long patternId) {
409 TemplateAccount result = new TemplateAccount(id, patternId, position);
411 if (accountName.hasLiteralValue())
412 result.setAccountName(accountName.getValue());
414 result.setAccountNameMatchGroup(accountName.getMatchGroup());
416 if (accountComment.hasLiteralValue())
417 result.setAccountComment(accountComment.getValue());
419 result.setAccountCommentMatchGroup(accountComment.getMatchGroup());
421 if (amount.hasLiteralValue()) {
422 result.setAmount(amount.getValue());
423 result.setNegateAmount(null);
426 result.setAmountMatchGroup(amount.getMatchGroup());
427 result.setNegateAmount(negateAmount ? true : null);
432 public boolean isEmpty() {
433 return accountName.isEmpty() && accountComment.isEmpty() && amount.isEmpty();
437 public static class Header extends TemplateDetailsItem {
438 private String pattern = "";
439 private String testText = "";
440 private String name = "";
441 private Pattern compiledPattern;
442 private String patternError;
443 private PossiblyMatchedValue<String> transactionDescription =
444 PossiblyMatchedValue.withLiteralString("");
445 private PossiblyMatchedValue<String> transactionComment =
446 PossiblyMatchedValue.withLiteralString("");
447 private PossiblyMatchedValue<Integer> dateYear = PossiblyMatchedValue.withLiteralInt(null);
448 private PossiblyMatchedValue<Integer> dateMonth = PossiblyMatchedValue.withLiteralInt(null);
449 private PossiblyMatchedValue<Integer> dateDay = PossiblyMatchedValue.withLiteralInt(null);
450 private SpannableString testMatch;
451 private boolean isFallback;
455 public Header(Header origin) {
459 testText = origin.testText;
460 testMatch = origin.testMatch;
461 setPattern(origin.pattern);
463 transactionDescription = new PossiblyMatchedValue<>(origin.transactionDescription);
464 transactionComment = new PossiblyMatchedValue<>(origin.transactionComment);
466 dateYear = new PossiblyMatchedValue<>(origin.dateYear);
467 dateMonth = new PossiblyMatchedValue<>(origin.dateMonth);
468 dateDay = new PossiblyMatchedValue<>(origin.dateDay);
470 isFallback = origin.isFallback;
472 private static StyleSpan capturedSpan() { return new StyleSpan(Typeface.BOLD); }
473 private static UnderlineSpan matchedSpan() { return new UnderlineSpan(); }
474 private static ForegroundColorSpan notMatchedSpan() {
475 return new ForegroundColorSpan(Color.GRAY);
477 public boolean isFallback() {
480 public void setFallback(boolean fallback) {
481 this.isFallback = fallback;
483 public String getName() {
486 public void setName(String name) {
489 public String getPattern() {
492 public void setPattern(String pattern) {
493 this.pattern = pattern;
495 this.compiledPattern = Pattern.compile(pattern);
498 catch (PatternSyntaxException ex) {
499 patternError = ex.getDescription();
500 compiledPattern = null;
502 testMatch = new SpannableString(testText);
503 if (!testText.isEmpty())
504 testMatch.setSpan(notMatchedSpan(), 0, testText.length() - 1,
505 Spanned.SPAN_INCLUSIVE_INCLUSIVE);
510 public String toString() {
511 return super.toString() +
512 String.format(" name[%s] pat[%s] test[%s] tran[%s] com[%s]", name, pattern,
513 testText, transactionDescription, transactionComment);
515 public String getTestText() {
518 public void setTestText(String testText) {
519 this.testText = testText;
523 public String getTransactionDescription() {
524 return transactionDescription.getValue();
526 public void setTransactionDescription(String transactionDescription) {
527 this.transactionDescription.setValue(transactionDescription);
529 public String getTransactionComment() {
530 return transactionComment.getValue();
532 public void setTransactionComment(String transactionComment) {
533 this.transactionComment.setValue(transactionComment);
535 public Integer getDateYear() {
536 return dateYear.getValue();
538 public void setDateYear(Integer dateYear) {
539 this.dateYear.setValue(dateYear);
541 public Integer getDateMonth() {
542 return dateMonth.getValue();
544 public void setDateMonth(Integer dateMonth) {
545 this.dateMonth.setValue(dateMonth);
547 public Integer getDateDay() {
548 return dateDay.getValue();
550 public void setDateDay(Integer dateDay) {
551 this.dateDay.setValue(dateDay);
553 public int getDateYearMatchGroup() {
554 return dateYear.getMatchGroup();
556 public void setDateYearMatchGroup(int dateYearMatchGroup) {
557 this.dateYear.setMatchGroup(dateYearMatchGroup);
559 public int getDateMonthMatchGroup() {
560 return dateMonth.getMatchGroup();
562 public void setDateMonthMatchGroup(int dateMonthMatchGroup) {
563 this.dateMonth.setMatchGroup(dateMonthMatchGroup);
565 public int getDateDayMatchGroup() {
566 return dateDay.getMatchGroup();
568 public void setDateDayMatchGroup(int dateDayMatchGroup) {
569 this.dateDay.setMatchGroup(dateDayMatchGroup);
571 public boolean hasLiteralDateYear() {
572 return dateYear.hasLiteralValue();
574 public boolean hasLiteralDateMonth() {
575 return dateMonth.hasLiteralValue();
577 public boolean hasLiteralDateDay() {
578 return dateDay.hasLiteralValue();
580 public boolean hasLiteralTransactionDescription() { return transactionDescription.hasLiteralValue(); }
581 public boolean hasLiteralTransactionComment() { return transactionComment.hasLiteralValue(); }
582 public String getProblem(@NonNull Resources r, int patternGroupCount) {
583 if (patternError != null)
584 return r.getString(R.string.pattern_has_errors) + ": " + patternError;
585 if (Misc.emptyIsNull(pattern) == null)
586 return r.getString(R.string.pattern_is_empty);
588 if (!dateYear.hasLiteralValue() && compiledPattern != null &&
589 (dateDay.getMatchGroup() < 1 || dateDay.getMatchGroup() > patternGroupCount))
590 return r.getString(R.string.invalid_matching_group_number);
592 if (!dateMonth.hasLiteralValue() && compiledPattern != null &&
593 (dateMonth.getMatchGroup() < 1 || dateMonth.getMatchGroup() > patternGroupCount))
594 return r.getString(R.string.invalid_matching_group_number);
596 if (!dateDay.hasLiteralValue() && compiledPattern != null &&
597 (dateDay.getMatchGroup() < 1 || dateDay.getMatchGroup() > patternGroupCount))
598 return r.getString(R.string.invalid_matching_group_number);
603 public boolean equalContents(Header o) {
604 if (!dateDay.equals(o.dateDay))
606 if (!dateMonth.equals(o.dateMonth))
608 if (!dateYear.equals(o.dateYear))
610 if (!transactionDescription.equals(o.transactionDescription))
612 if (!transactionComment.equals(o.transactionComment))
615 return Misc.equalStrings(name, o.name) && Misc.equalStrings(pattern, o.pattern) &&
616 Misc.equalStrings(testText, o.testText) &&
617 Misc.equalStrings(patternError, o.patternError) &&
618 Objects.equals(testMatch, o.testMatch) && isFallback == o.isFallback;
620 public String getMatchGroupText(int group) {
621 if (compiledPattern != null && testText != null) {
622 Matcher m = compiledPattern.matcher(testText);
624 return m.group(group);
629 public Pattern getCompiledPattern() {
630 return compiledPattern;
632 public void switchToLiteralTransactionDescription() {
633 transactionDescription.switchToLiteral();
635 public void switchToLiteralTransactionComment() {
636 transactionComment.switchToLiteral();
638 public int getTransactionDescriptionMatchGroup() {
639 return transactionDescription.getMatchGroup();
641 public void setTransactionDescriptionMatchGroup(int group) {
642 transactionDescription.setMatchGroup(group);
644 public int getTransactionCommentMatchGroup() {
645 return transactionComment.getMatchGroup();
647 public void setTransactionCommentMatchGroup(int group) {
648 transactionComment.setMatchGroup(group);
650 public void switchToLiteralDateYear() {
651 dateYear.switchToLiteral();
653 public void switchToLiteralDateMonth() {
654 dateMonth.switchToLiteral();
656 public void switchToLiteralDateDay() { dateDay.switchToLiteral(); }
657 public TemplateHeader toDBO() {
658 TemplateHeader result = new TemplateHeader(id, name, pattern);
660 if (Misc.emptyIsNull(testText) != null)
661 result.setTestText(testText);
663 if (transactionDescription.hasLiteralValue())
664 result.setTransactionDescription(transactionDescription.getValue());
666 result.setTransactionDescriptionMatchGroup(transactionDescription.getMatchGroup());
668 if (transactionComment.hasLiteralValue())
669 result.setTransactionComment(transactionComment.getValue());
671 result.setTransactionCommentMatchGroup(transactionComment.getMatchGroup());
673 if (dateYear.hasLiteralValue())
674 result.setDateYear(dateYear.getValue());
676 result.setDateYearMatchGroup(dateYear.getMatchGroup());
678 if (dateMonth.hasLiteralValue())
679 result.setDateMonth(dateMonth.getValue());
681 result.setDateMonthMatchGroup(dateMonth.getMatchGroup());
683 if (dateDay.hasLiteralValue())
684 result.setDateDay(dateDay.getValue());
686 result.setDateDayMatchGroup(dateDay.getMatchGroup());
688 result.setFallback(isFallback);
692 public SpannableString getTestMatch() {
695 public void checkPatternMatch() {
699 if (pattern != null) {
701 if (Misc.emptyIsNull(testText) != null) {
702 SpannableString ss = new SpannableString(testText);
703 Matcher m = compiledPattern.matcher(testText);
706 ss.setSpan(notMatchedSpan(), 0, m.start(),
707 Spanned.SPAN_INCLUSIVE_INCLUSIVE);
708 if (m.end() < testText.length() - 1)
709 ss.setSpan(notMatchedSpan(), m.end(), testText.length(),
710 Spanned.SPAN_INCLUSIVE_INCLUSIVE);
712 ss.setSpan(matchedSpan(), m.start(0), m.end(0),
713 Spanned.SPAN_INCLUSIVE_INCLUSIVE);
715 if (m.groupCount() > 0) {
716 for (int g = 1; g <= m.groupCount(); g++) {
717 ss.setSpan(capturedSpan(), m.start(g), m.end(g),
718 Spanned.SPAN_INCLUSIVE_INCLUSIVE);
723 patternError = "Pattern does not match";
724 ss.setSpan(new ForegroundColorSpan(Color.GRAY), 0,
725 testText.length() - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
731 catch (PatternSyntaxException e) {
732 this.compiledPattern = null;
733 this.patternError = e.getMessage();
737 patternError = "Missing pattern";
740 public String getPatternError() {
743 public SpannableString testMatch() {