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

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

import de.ivu.elect.business.gebietsbaum.control.GebietByNummerComparator;
import de.ivu.elect.business.gebietsbaum.entity.Gebiet;
import de.ivu.elect.business.wahl.control.WahlByWahldatumAscAndPositionAscComparator;
import de.ivu.elect.business.wahl.entity.Wahl;
import de.ivu.elect.business.wahlvorschlag.control.WahlvorschlagByKennwortComparator;
import de.ivu.elect.business.wahlvorschlag.entity.Wahlvorschlag;
import de.ivu.elect.business.wahlvorschlagsperson.entity.WahlvorschlagsPerson;

public class WahlvorschlagsPersonByWahlvorschlagAndEingangssequenznummerComparator implements Comparator<WahlvorschlagsPerson>, Serializable {

  private static final long serialVersionUID = 1L;

  private static final Comparator<Wahl> WAHL_COMPARATOR = new WahlByWahldatumAscAndPositionAscComparator();

  private static final Comparator<Gebiet> GEBIET_COMPARATOR = GebietByNummerComparator.ASCENDING;

  private static final Comparator<Wahlvorschlag> WAHLVORSCHLAG_COMPARATOR = new WahlvorschlagByKennwortComparator();

  private static final Comparator<WahlvorschlagsPerson> EINGANGSSEQUENZNUMMER_COMPARATOR = new WahlvorschlagsPersonByEingangssequenznummerComparator();

  @Override
  public int compare(WahlvorschlagsPerson one, WahlvorschlagsPerson another) {
    if (one != null && another != null) {
      int comparedByWahl = compare(one.getWahl(), another.getWahl());

      if (comparedByWahl == 0) {
        int comparedByWahlvorschlag = compare(one.getWahlvorschlag(), another.getWahlvorschlag());

        if (comparedByWahlvorschlag == 0) {
          return EINGANGSSEQUENZNUMMER_COMPARATOR.compare(one, another);
        }

        return comparedByWahlvorschlag;
      }

      return comparedByWahl;
    }

    if (one == null) {
      if (another == null) {
        return 0;
      }

      return -1;
    }

    return 1;
  }

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

    if (one == null) {
      if (another == null) {
        return 0;
      }

      return -1;
    }

    return 1;
  }

  private int compare(Wahlvorschlag one, Wahlvorschlag another) {
    if (one != null && another != null) {
      int comparedByGebiet = compare(one.getGebiet(), another.getGebiet());

      if (comparedByGebiet == 0) {
        return WAHLVORSCHLAG_COMPARATOR.compare(one, another);
      }

      return comparedByGebiet;
    }

    if (one == null) {
      if (another == null) {
        return 0;
      }

      return -1;
    }

    return 1;
  }

  private int compare(Gebiet one, Gebiet another) {
    return GEBIET_COMPARATOR.compare(one, another);
  }
}
