
package de.ivu.elect.business.gruppe.control;

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

import java.io.Serializable;
import java.util.Comparator;
import java.util.function.Supplier;

import javax.annotation.Nonnull;

import de.ivu.elect.jee.entity.Entity;
import de.ivu.elect.util.CaseAndDiacriticIgnoringComparator;
import de.ivu.elect.util.NullComparator;

public class GruppeNamenComparator implements Comparator<String>, Serializable {

  private static final long serialVersionUID = 1L;

  private static final String REG_EX_NOT_APLPHANUMERIC = "[^\\p{L}\\p{N}]";

  public static final GruppeNamenComparator DEFAULT_INSTANCE = new GruppeNamenComparator();

  private static final Comparator<String> DEFAULT_COMPARATOR = CaseAndDiacriticIgnoringComparator.DEFAULT_INSTANCE;

  public GruppeNamenComparator() {
    super();
  }

  public int compare(@Nonnull Entity< ? , ? > one, Supplier<String> oneNamenSupplier, @Nonnull Entity< ? , ? > another, Supplier<String> anotherNamenSupplier) {
    int comparedByNamen = compare(oneNamenSupplier.get(), anotherNamenSupplier.get());

    if (comparedByNamen == 0) {
      return compare(one.getId(), another.getId());
    }

    return comparedByNamen;
  }

  private int compare(Long one, Long another) {
    if (one != null && another != null) {
      return one.compareTo(another);
    }

    return NullComparator.NULL_BEFORE_NON_NULL_COMPARATOR.compare(one, another);
  }

  @Override
  public int compare(String one, String another) {
    return DEFAULT_COMPARATOR.compare(normalize(one), normalize(another));
  }

  // WASDE-1334
  protected String normalize(String value) {
    String result = trimToEmpty(value);
    result = result.replaceAll(REG_EX_NOT_APLPHANUMERIC, "");

    return trimToEmpty(result);
  }
}
