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

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

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

import javax.annotation.Nullable;

import de.ivu.elect.business.gruppe.entity.Gruppe;
import de.ivu.elect.util.NullComparator;

public class GruppeByKurznameComparator<G extends Gruppe> implements Comparator<G>, Serializable {

  private static final long serialVersionUID = 1L;

  public static final Comparator<Gruppe> ASCENDING = new GruppeByKurznameComparator<>();

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

  // WASDE-1334
  private static final GruppeNamenComparator GRUPPE_NAMEN_COMPARATOR = GruppeNamenComparator.DEFAULT_INSTANCE;

  public GruppeByKurznameComparator() {
    super();
  }

  @Override
  public int compare(@Nullable G one, @Nullable G another) {
    if (one != null && another != null) {
      return GRUPPE_NAMEN_COMPARATOR.compare(one, () -> getKurznameOderName(one), another, () -> getKurznameOderName(another));
    }

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

  public static String getKurznameOderName(Gruppe gruppe) {
    if (gruppe == null) {
      return "";
    }

    if (isNotBlank(gruppe.getKurzname()) && !"-".equals(gruppe.getKurzname())) {
      return gruppe.getKurzname();
    }

    return gruppe.getName();
  }
}
