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

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

import de.ivu.elect.business.benutzerverwaltung.entity.Rolle;
import de.ivu.elect.business.security.UseCasePermission;

@Stateless
@Specializes
public class BaseRolleBoundaryCreate extends RolleBoundaryCreate {

  @Inject
  private transient RolleDAO rolleDAO;

  public Rolle copy(Rolle entityNotAttched) {
    Rolle entity = rolleDAO.attach(entityNotAttched);
    Rolle copy = new Rolle();
    entity.copyEntityAttributesUsingSetter(copy);

    copy.setMandant(entity.getMandant());
    copy.setName(copy.getName() + " (copy)");

    for (UseCasePermission useCasePermission : entity.getRecht()) {
      copy.addRecht(useCasePermission);
    }

    while (rolleSchonVorhanden(copy)) {
      copy.setName(copy.getName() + "#");
    }

    save(copy);

    return copy;

  }

  private boolean rolleSchonVorhanden(Rolle copy) {
    return !rolleDAO.findByName(copy.getMandant(), copy.getName()).isEmpty();
  }
}
