
package de.ivu.elect.business.protokollierung.entity;

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

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

import de.ivu.elect.jee.faces.Messages;
import de.ivu.elect.util.CaseAndDiacriticIgnoringComparator;

public class ProtokollEintragDefaultComparator implements Comparator<ProtokollEintrag>, Serializable {

  private static final long serialVersionUID = 1L;

  private static final Comparator<String> STRING_DEFAULT_COMPARATOR = CaseAndDiacriticIgnoringComparator.DEFAULT_INSTANCE;

  private final Messages messages;

  public ProtokollEintragDefaultComparator(Messages messages) {
    super();

    this.messages = messages;
  }

  @Override
  public int compare(ProtokollEintrag one, ProtokollEintrag another) {
    int result = compareByZeitpunkt(one, another);

    if (result == 0) {
      result = STRING_DEFAULT_COMPARATOR.compare(one.getEntitaet(), another.getEntitaet());
    }

    if (result == 0) {
      result = another.getPrimaerschluessel().compareTo(one.getPrimaerschluessel());
    }

    if (result == 0) {
      result = compareByAttribut(one.getAttribut(), another.getAttribut());
    }

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

    return result;
  }

  private int compareByZeitpunkt(ProtokollEintrag one, ProtokollEintrag another) {
    return asCalendar(another.getZeitpunkt()).compareTo(asCalendar(one.getZeitpunkt()));
  }

  private Calendar asCalendar(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.clear(Calendar.MILLISECOND);

    return calendar;
  }

  private int compareByAttribut(String one, String another) {
    return STRING_DEFAULT_COMPARATOR.compare(getMessage(one), getMessage(another));
  }

  private String getMessage(String msgKey) {
    if (isNotBlank(msgKey)) {
      return messages.getMessageForMessageKey(msgKey);
    }

    return msgKey;
  }
}
