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

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

import javax.annotation.Nullable;

import de.ivu.elect.business.gebietsbaum.entity.Gebiet;
import de.ivu.elect.util.NullComparator;

public class GebietByNummerComparator implements Comparator<Gebiet>, Serializable {

  private static final long serialVersionUID = 1L;

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

  public static final Comparator<Gebiet> ASCENDING = new GebietByNummerComparator();

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

  private GebietByNummerComparator() {
    super();
  }

  @Override
  public int compare(Gebiet one, Gebiet another) {
    if (one == null || another == null) {
      return NULL_COMPARATOR.compare(one, another);
    }

    int comparedByNummer = compareNummer(one.getNummer(), another.getNummer());

    if (comparedByNummer == 0) {
      return one.getPk().compareTo(another.getPk());
    }

    return comparedByNummer;
  }

  public static int compareNummer(String one, String another) {
    if (one == null || another == null) {
      return NULL_COMPARATOR.compare(one, another);
    }

    Long oneAsLong = tryParse(one);
    Long anotherAsLong = tryParse(another);

    if (oneAsLong == null && anotherAsLong == null) {
      return one.compareTo(another);
    }

    if (oneAsLong == null || anotherAsLong == null) {
      return NULL_COMPARATOR.compare(oneAsLong, anotherAsLong);
    }

    return oneAsLong.compareTo(anotherAsLong);
  }

  @Nullable
  private static Long tryParse(String one) {
    try {
      return Long.parseLong(one);
    } catch (Exception ignored) {
    }

    return null;
  }
}
