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

import java.util.List;
import java.util.stream.Collectors;

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

import de.ivu.elect.business.benutzerverwaltung.entity.QRolle;
import de.ivu.elect.business.benutzerverwaltung.entity.Rolle;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.security.control.ElectExtendedUseCasePermissionFilter;
import de.ivu.elect.jee.entity.QueryDsl;


import static de.ivu.elect.business.benutzerverwaltung.boundary.PermissionService.isNotwendigeRechteVorhanden;

@Stateless
public class RolleSearch extends AbstractRolleSearch {

  @Inject
  private transient ElectExtendedUseCasePermissionFilter extendedElectUseCasePermissionFilter;

  public RolleSearch() {
    super();
  }

  @Override
  protected List<Rolle> querySearchResult(RolleSearchParameters searchParameters) {
    QueryDsl queryDsl = dao.getQueryDsl();

    QRolle rolle = QRolle.rolle;

    queryDsl.from(rolle);
    queryDsl.eq(rolle.mandant, searchParameters.getMandant());
    queryDsl.likeIfNotBlank(rolle.name, searchParameters.getName());
    queryDsl.likeIfNotBlank(rolle.beschreibung, searchParameters.getBeschreibung());

    queryDsl.getQuery().orderBy(rolle.name.asc());

    List<Rolle> result = queryDsl.list(rolle);

    // ELECTKOM-1014
    result = result.stream()
            .filter(r -> searchParameters.getVorhandeneRechte().contains(UseCasePermission.ROLLE_SEARCH_ALL)/* ELECT-12577*/ ||isNotwendigeRechteVorhanden(r.getRecht(),
                    searchParameters.getVorhandeneRechte(),
                    extendedElectUseCasePermissionFilter,
                    searchParameters.getMandant().getPk()))
            .collect(Collectors.toList());

    if (searchParameters.getRolleArt() != null) {
      result = result.stream().filter(s -> searchParameters.getRolleArt().equals(s.getRolleArt())).collect(Collectors.toList());
    }

    return result;
  }
}
