package com.tecgraf.dao;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;

/**
 * Singleton FacadeJPA
 * 
 * @author Ismael H F Santos
 */
public class FacadeJPA {
  public static FacadeJPA getInstance( String persitenceUnit ) {
    if( instance == null ) {
      instance = new FacadeJPA(persitenceUnit);
    }
    return instance;
  }

  //--------------------------------------------------
  // Public methods
  //--------------------------------------------------
  public void setPersitenceUnit( String persistUnit ) {
    if( persistenceUnit == null || !persistenceUnit.equals(persistUnit) ) {
      try {
        persistenceUnit = persistUnit;
        // Save previoulsy allocated entityManagerFactory and entityManager
        if( entityManagerFactory != null ) {
          entityManagerFactory.close();
          entityManagerFactory = null;
        }
        // Allocate new entityManagerFactory and entityManager
        entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnit);

      } catch( PersistenceException pEx ) {
        pEx.printStackTrace();
        if( entityManagerFactory != null ) {
          entityManagerFactory.close();
          entityManagerFactory = null;
        }
      } catch( Exception ex ) {
        ex.printStackTrace();
        if( entityManagerFactory != null ) {
          entityManagerFactory.close();
          entityManagerFactory = null;
        }
      }
    }
  }

  public void shutdown() {
    if( entityManagerFactory != null ) {
      entityManagerFactory.close();
      entityManagerFactory = null;
    }
    try {
      super.finalize();
    } catch( Throwable ex ) {
      Logger.getLogger(FacadeJPA.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  public EntityManagerFactory getEntityManagerFactory() {
    return entityManagerFactory;
  }
  //--------------------------------------------------
  // Private methods
  //--------------------------------------------------
  private FacadeJPA( String persitenceUnit ) {
    this.setPersitenceUnit(persitenceUnit);
  }  //--------------------------------------------------
  // Private atributes
  //--------------------------------------------------
  private static FacadeJPA instance = null;
  private EntityManagerFactory entityManagerFactory;
  private String persistenceUnit;
}

