
package de.ivu.elect.util;

import java.io.Serializable;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.Comparator;
import java.util.Locale;


import static org.apache.commons.lang3.StringUtils.isNotBlank;

public class AbstractCollatorComparator implements Comparator<String>, Serializable {

  private static final long serialVersionUID = 1L;

  private final transient Collator collator;

  public AbstractCollatorComparator(Collator collator) {
    super();

    this.collator = collator;
  }

  private Collator getCollator() {
    return collator;
  }

  @Override
  public int compare(String one, String another) {
    if (one != null && another != null) {
      return getCollator().compare(normalizeValue(one), normalizeValue(another));
    }

    if (one == null) {
      if (another == null) {
        return 0;
      }

      return -1;
    }

    return 1;
  }

  protected String normalizeValue(String value) {
    return normalizeWhitespaces(value);
  }

  private String normalizeWhitespaces(String value) {
    // NOTE ELECT-3776, dass der Collator standardmäßig Leerzeichen ignoriert!
    return value.replaceAll("\\s+", "_");
  }

  protected static Collator createCollator(Locale locale, int strength, String rules) {
    Collator collator = Collator.getInstance(locale);

    if (isNotBlank(rules)) {
      try {
        collator = new RuleBasedCollator(((RuleBasedCollator) collator).getRules() + rules);
      } catch (Exception ex) {
        throw new IllegalArgumentException("FAILED to instantiated RuleBasedCollator ", ex);
      }
    }

    collator.setStrength(strength);

    return collator;
  }
}
