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

import de.ivu.elect.business.benutzerverwaltung.boundary.RolleDAO;
import de.ivu.elect.business.benutzerverwaltung.boundary.RolleExtendedDAO;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.NoResultException;
import java.io.Serializable;

@Stateless
public class UniqueRolleUKValidator implements Serializable {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient RolleDAO rolleDAO;

  @Inject
  private transient RolleExtendedDAO rolleExtendedDAO;

  public UniqueRolleUKValidator() {
    super();
  }

  public boolean isUniqueRolleUK(Rolle entity) {
    try {
      return getRolleByUK(entity).getPk().equals(entity.getPk());
    } catch (NoResultException ignored) {
      // Do nothing - be happy.
    }
    return true;
  }

  public boolean isUniqueRolleUKExtendedPersistenceContext(Rolle entity) {
    try {
      return getRolleByUKExtendedPersistenceContext(entity).getPk().equals(entity.getPk());
    } catch (NoResultException ignored) {
      // Do nothing - be happy.
    }
    return true;
  }

  private Rolle getRolleByUK(Rolle rolle) {
    return rolleDAO.findByNameUpper(rolle.getMandant(), rolle.getName());
  }

  private Rolle getRolleByUKExtendedPersistenceContext(Rolle rolle) {
    return rolleExtendedDAO.findByNameUpper(rolle.getMandant(), rolle.getName());
  }
}
