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

import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;

import de.ivu.elect.business.person.entity.EntityMitPersonendaten;
import de.ivu.elect.business.person.entity.Personendaten;
import de.ivu.elect.jee.entity.Entity;
import de.ivu.elect.util.CaseAndDiacriticIgnoringComparator;
import de.ivu.elect.util.NullComparator;

public class EntityMitPersonendatenByNamenComparator<E extends Entity< ? , ? > & EntityMitPersonendaten> implements Comparator<E>, Serializable {

  private static final long serialVersionUID = 1L;

  public static final Comparator<Personendaten> ASCENDING = new EntityMitPersonendatenByNamenComparator<>();

  public static final Comparator<Personendaten> DESCENDING = Collections.reverseOrder(ASCENDING);

  private static final Comparator<Object> NULL_COMPARATOR = NullComparator.NULL_BEFORE_NON_NULL_COMPARATOR;

  public EntityMitPersonendatenByNamenComparator() {
    super();
  }

  @Override
  public int compare(E one, E another) {
    if (one != null && another != null) {
      int comparedByFamilienname = compare(one.getFamilienname(), another.getFamilienname());

      if (comparedByFamilienname == 0) {
        int comparedByRufname = compare(one.getRufname(), another.getRufname());

        if (comparedByRufname == 0) {
          return compare(one.getId(), another.getId()); // ELECTKOM-535
        }

        return comparedByRufname;
      }

      return comparedByFamilienname;
    }

    return NULL_COMPARATOR.compare(one, another);
  }

  private int compare(String one, String another) {
    return CaseAndDiacriticIgnoringComparator.DEFAULT_INSTANCE.compare(one, another);
  }

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

    return NULL_COMPARATOR.compare(one, another);
  }
}
