
package de.ivu.elect.jee.presentation.search;

import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.apache.commons.lang3.StringUtils.endsWithIgnoreCase;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.splitByWholeSeparator;
import static org.apache.commons.lang3.StringUtils.startsWithIgnoreCase;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;

import java.util.regex.Pattern;

public class WildcardConverter {

  public static final String WILDCARD_CHARACTER_DEFAULT = "*";

  public static final String WILDCARD_CHARACTER_DEFAULT_REGEX = Pattern.quote(WILDCARD_CHARACTER_DEFAULT);

  public static final String WILDCARD_CHARACTER_JPQL = "%";

  public WildcardConverter() {
    super();
  }

  /**
   * Wandelt den Wildcard aus der Oberfläche (*) zu dem bei JPQL verwendeten Wildcard (%) um. Der Wildcard kann am Anfang und/oder am Ende stehen. Wird null oder blank übergeben, so wird "%" zurück
   * gegeben.
   *
   * e.g. "Albert*" wird zu "Albert%%"
   */
  public String addAndConvertToJpqlLikeExpression(String string) {
    return convertToJpqlLikeExpression(defaultString(string, "") + WILDCARD_CHARACTER_DEFAULT);
  }

  public String convertToJpqlLikeExpression(String string) {
    return defaultString(string, "").replaceAll(WILDCARD_CHARACTER_DEFAULT_REGEX, WILDCARD_CHARACTER_JPQL).trim();
  }

  public String addAndConvertToStringMatcherExpression(String string) {
    String result = convertToStringMatcherExpression(string);

    if (!endsWithIgnoreCase(result, WILDCARD_CHARACTER_DEFAULT)) {
      String stringMatcherWildcardRegEx = ".*";

      result += stringMatcherWildcardRegEx;
    }

    return result;
  }

  public String convertToStringMatcherExpression(String string) {
    StringBuilder result = new StringBuilder();

    String stringMatcherWildcardRegEx = ".*";
    String stringNormalized = trimToEmpty(string);

    result.append("(?i)"); // IgnoreCase!

    if (startsWithIgnoreCase(stringNormalized, WILDCARD_CHARACTER_DEFAULT)) {
      result.append(stringMatcherWildcardRegEx);
    }

    for (String part : splitByWholeSeparator(stringNormalized, WILDCARD_CHARACTER_DEFAULT)) {
      if (isNotBlank(part)) {
        result.append(Pattern.quote(part));
        result.append(stringMatcherWildcardRegEx);
      }
    }

    return result.toString();
  }
}
