
package de.ivu.elect.presentation.ergebnis.dokumente.gesamtergebnis;

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

import de.ivu.elect.util.NullComparator;

public class KandidaturDocumentByStimmenComparator implements Comparator<KandidaturMitStimmergebnissenDocument>, Serializable {

  private static final long serialVersionUID = 1L;

  public static final Comparator<KandidaturMitStimmergebnissenDocument> DESCENDING = new KandidaturDocumentByStimmenComparator();

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

  private static final Comparator<KandidaturMitStimmergebnissenDocument> POSITION_COMPARATOR = KandidaturDocumentByPositionComparator.ASCENDING;

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

  private KandidaturDocumentByStimmenComparator() {
    super();
  }

  @Override
  public int compare(KandidaturMitStimmergebnissenDocument one, KandidaturMitStimmergebnissenDocument another) {
    if (one != null && another != null) {
      int comparedByStimmen = compareDesc(one.anzahlGueltigerStimmen, another.anzahlGueltigerStimmen);

      if (comparedByStimmen == 0) { // ELECT-14202
        return POSITION_COMPARATOR.compare(one, another);
      }

      return comparedByStimmen;
    }

    return NULL_COMPARATOR.compare(one, another);
  }

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

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