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

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.Transient;

import de.ivu.elect.business.benutzerverwaltung.boundary.AbstractRolleDAO;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.business.security.entity.RolleTemplate;
import de.ivu.elect.jee.faces.Messages;


import static java.util.Objects.isNull;

public abstract class AbstractRolle implements RolleBase {

  private static final long serialVersionUID = 6873043806050099384L;

  @Transient
  private transient RollePermissionPickListProperty rollePermissionPickListProperty;

  public AbstractRolle() {
    super();
  }

  public void addPermissions(List<UseCasePermission> perms) {
    for (UseCasePermission electCommonPermission : perms) {
      addRecht(electCommonPermission);
    }
  }

  public RollePermissionPickListProperty getRollePermissionPickListProperty(List<UseCasePermission> verfuegbareRechte, Messages messages) {
    if (isNull(rollePermissionPickListProperty)) {
      rollePermissionPickListProperty = new RollePermissionPickListProperty((Rolle) this, verfuegbareRechte, messages);
    }

    return rollePermissionPickListProperty;
  }

  public boolean isGebietRolle() {
    return RolleArt.GEBIET.equals(getRolleArt());
  }

  public boolean isWahlRolle() {
    return RolleArt.WAHL.equals(getRolleArt());
  }

  public boolean isFachlicheRolle() {
    return getRolleArt().isFachlich();
  }

  public boolean isStandardRolle(Collection<? extends RolleTemplate> anzulegendeKundenRollen) {
    return anzulegendeKundenRollen.stream().anyMatch(rolleTemplate -> rolleTemplate.getRolleName().equalsIgnoreCase(getName()));
  }

  public static Rolle createRolleFrom(RolleTemplate rolleTemplate) {
    Rolle rolle = new Rolle();
    rolle.setName(rolleTemplate.getRolleName());

    return rolle;
  }

  public boolean isAdminRolle() {
    return RolleTemplate.ADMIN.getRolleName().equalsIgnoreCase(getName());
  }

  public void removeAllRechts() {
    // ELECT-9775
    removeAllRechtAsStrings();
  }

  public Set<UseCasePermission> getRecht() {
    Set<UseCasePermission> result = new HashSet<>();
    for (String useCasePermissionAsString : getRechtAsString()) {
      try {
        result.add(UseCasePermission.valueOf(useCasePermissionAsString));
      } catch (Exception e) {
        // ELECT-9775
        // ignorieren
      }
    }
    return result;
  }

  public void addRecht(UseCasePermission useCasePermission) {
    addRechtAsString(useCasePermission.name());
  }

  public void removeRecht(UseCasePermission useCasePermission) {
    removeRechtAsString(useCasePermission.name());
  }

}
