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

import java.util.Comparator;
import java.util.Optional;

import de.ivu.elect.business.konfiguration.entity.CustomParameter;
import de.ivu.elect.business.konfiguration.entity.CustomParameterTemplate;
import de.ivu.elect.jee.cdi.BeanManagerUtil;
import de.ivu.elect.jee.faces.Messages;
import de.ivu.elect.util.CaseAndDiacriticIgnoringComparator;

public class CustomParameterByTemplateComparator<T extends CustomParameterTemplate> implements Comparator<CustomParameter<T>> {

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

  public CustomParameterByTemplateComparator() {
    super();
  }

  @Override
  public int compare(CustomParameter<T> one, CustomParameter<T> another) {
    Optional<T> oneTemplate = one.getTemplate();
    Optional<T> anotherTemplate = another.getTemplate();

    if (oneTemplate.isPresent()) {
      if (anotherTemplate.isPresent()) {
        int comparedByTemplate = compareByTemplate(oneTemplate.get(), anotherTemplate.get());

        if (comparedByTemplate == 0) {
          return DEFAULT_STRING_COMPARATOR.compare(one.getName(getMessages()), another.getName(getMessages()));
        }

        return comparedByTemplate;
      } else {
        return -1;
      }
    } else {
      if (anotherTemplate.isPresent()) {
        return 1;
      } else {
        return 0;
      }
    }
  }

  private int compareByTemplate(T one, T another) {
    int comparedByKategorie = one.getKategorie().ordinal() - another.getKategorie().ordinal();

    if (comparedByKategorie == 0 && one.getKategorie().isOrderedByPosition()) {
      return one.getKategoriePosition() - another.getKategoriePosition();
    }

    return comparedByKategorie;
  }

  protected Messages getMessages() {
    return BeanManagerUtil.getBeanByClass(Messages.class);
  }
}
