package de.ivu.elect.presentation.benutzerverwaltung;

import de.ivu.elect.business.benutzerverwaltung.boundary.PermissionService;
import de.ivu.elect.business.benutzerverwaltung.boundary.RolleExtendedDAO;
import de.ivu.elect.business.benutzerverwaltung.entity.Rolle;
import de.ivu.elect.business.mandant.entity.MandantPK;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.security.control.ElectCommonPrincipal;
import de.ivu.elect.business.security.control.ElectExtendedUseCasePermissionFilter;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import java.io.Serializable;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

@RequestScoped
public class PermissionServiceHelper implements Serializable {
  private static final long serialVersionUID = 1L;

  @Inject
  private transient RolleExtendedDAO rolleExtendedDAO;

  @Inject
  private transient ElectCommonPrincipal principal;

  @Inject
  private transient ElectExtendedUseCasePermissionFilter extendedElectUseCasePermissionFilter;

  public Set<Rolle> getAlleRollenDieVomPrincipalZugewiesenWerdenKoennen() {
    return filterRollenMitUebergebenenRechten(rolleExtendedDAO.findByAll(principal.getMandant()), principal.getUseCasePermissions(), principal.getMandantPK());
  }

  private Set<Rolle> filterRollenMitUebergebenenRechten(Collection<Rolle> rollen, Collection<UseCasePermission> rechte, MandantPK mandantPK) {
    return rollen.stream().filter(rolle -> isRolleHatNurDieseRechte(rolle, rechte, mandantPK)).collect(Collectors.toSet());
  }

  boolean isRolleHatNurDieseRechte(Rolle rolle, Collection<UseCasePermission> rechte, MandantPK mandantPK) {
    return PermissionService.isNotwendigeRechteVorhanden(rolle.getRecht(), rechte, extendedElectUseCasePermissionFilter, mandantPK);
  }

}
