package de.ivu.elect.jee.database;

import java.util.Locale;

import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;

/**
 *  on 26.05.2017.
 */
@Stateless
public class DatasourceJndiResolver {

  @PersistenceContext
  private transient javax.persistence.EntityManager entityManager;


  public String getJndiName() {
    String puName = entityManager.getEntityManagerFactory().getProperties().get("hibernate.ejb.persistenceUnitName").toString();
    String puNameFirstUpper = puName.substring(0, 1).toUpperCase(Locale.GERMANY) + puName.substring(1);
    return "java:/elect" + puNameFirstUpper + "Database";
  }

  public DataSource getDatasource() {
    try {
      Context ctx = new InitialContext();
      return (DataSource) ctx.lookup(getJndiName());
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }

}
