
package de.ivu.elect.business.email.boundary;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;

import de.ivu.elect.business.email.entity.Email;
import de.ivu.elect.business.email.entity.QEmail;
import de.ivu.elect.business.person.control.EntityMitPersonendatenByNamenComparator;
import de.ivu.elect.business.person.entity.Personendaten;
import de.ivu.elect.business.person.entity.QPersonendaten;
import de.ivu.elect.jee.entity.QueryDsl;

@Stateless
public class EmailSearch extends AbstractEmailSearch {

  private static final Comparator<Personendaten> PERSONENDATEN_DEFAULT_COMPARATOR = new EntityMitPersonendatenByNamenComparator<>();

  private static final Comparator<Email> DEFAULT_COMPARATOR = (one, another) -> PERSONENDATEN_DEFAULT_COMPARATOR.compare(one.getPersonendaten(), another.getPersonendaten());

  @Inject
  private transient EmailVorgangConversationSelect emailVorgangConversationSelect;

  public EmailSearch() {
    super();
  }

  @Override
  protected List<Email> querySearchResult(EmailSearchParameters searchParameters) {
    List<Email> result = new ArrayList<>();

    QueryDsl queryDsl = dao.getQueryDsl();

    QEmail email = QEmail.email;

    queryDsl.from(email);

    queryDsl.eqIfNotNull(email.status, searchParameters.getStatus());
    queryDsl.likeIfNotBlank(email.empfaenger, searchParameters.getEmpfaenger());
    queryDsl.likeIfNotBlank(email.fehlermeldung, searchParameters.getFehlermeldung());

    QPersonendaten personendaten = email.personendaten;

    queryDsl.likeNormalizedIfNotBlank(personendaten.familiennameNormalisiert, searchParameters.getFamilienname());
    queryDsl.likeInAnyNormalizedIfNotBlank(personendaten.rufnameNormalisiert, personendaten.vornamenNormalisiert, searchParameters.getVornameSeparator(), searchParameters.getVorname());

    queryDsl.eqIfNotNull(email.emailVorgang, emailVorgangConversationSelect.getEntity());

    result.addAll(queryDsl.list(email));
    result.sort(getEmailComparator());

    return result;
  }

  protected Comparator<Email> getEmailComparator() {
    return DEFAULT_COMPARATOR;
  }
}
