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

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

import java.util.List;

import javax.ejb.Stateless;

import de.ivu.elect.business.geodata.entity.GeodataOrt;
import de.ivu.elect.business.geodata.entity.QGeodataOrt;
import de.ivu.elect.business.geodata.entity.QGeodataPlz;
import de.ivu.elect.jee.entity.QueryDsl;

@Stateless
public class GeodataOrtSearch extends AbstractGeodataOrtSearch {

  public GeodataOrtSearch() {
    super();
  }

  @Override
  protected List<GeodataOrt> querySearchResult(GeodataOrtSearchParameters searchParameters) {
    QGeodataOrt geodataOrt = QGeodataOrt.geodataOrt;

    QueryDsl queryDsl = dao.getQueryDsl();
    queryDsl.from(geodataOrt);

    queryDsl.likeIfNotBlank(geodataOrt.ortsname, searchParameters.getOrtsname());
    queryDsl.likeIfNotBlank(geodataOrt.ortsteilname, searchParameters.getOrtsteilname());

    if (isNotBlank(searchParameters.getPlz())) {
      QGeodataPlz geodataPlz = QGeodataPlz.geodataPlz;

      queryDsl.getQuery().innerJoin(geodataOrt.geodataPlzs, geodataPlz).where(geodataPlz.plz.like(convertSearchPattern(searchParameters.getPlz())));
    }

    queryDsl.orderBy(geodataOrt.ortsname.asc(), geodataOrt.ortsteilname.asc());

    return queryDsl.list(geodataOrt);
  }
}
