package versao3.persistencia;

import java.util.HashMap;
import java.util.Map;
import versao3.Configuration;
import versao3.persistencia.impl.jds.JDSDAOFactoryImpl;
import versao3.persistencia.impl.xml.XMLDAOFactoryImpl;

/**
 * Fábrica abstrata de DAOs.
 */
public abstract class DAOFactory {
  /**
   * @label Singleton 
   */
  public static DAOFactory instance;

  // Mapa de nomes de configuracao para fabricas concretas de DAOs.
  public static Map factories = new HashMap();
  static{
    factories.put(Configuration.JDATASTORE, JDSDAOFactoryImpl.class);
    factories.put(Configuration.XML,XMLDAOFactoryImpl.class);
  }

  /**
   * Obtem uma fabrica concreta de DAO, do tipo especificado na configuraçao.
   */
  public static synchronized DAOFactory getDAOFactory() throws PersistanceException{
    return getDAOFactory(Configuration.getInstance().getPersistenceType());
  }

  public static DAOFactory getDAOFactory(String whichFactory) throws
      PersistanceException {
    if (instance == null){
      try {
        Class clazz = (Class) factories.get(whichFactory);
        Object objFac = clazz.newInstance();
        if (objFac instanceof DAOFactory) {
          instance = ((DAOFactory) objFac);
        }
        else {
          throw new IllegalArgumentException();
        }
      }
      catch (InstantiationException ex) {
        throw new PersistanceException(ex);
      }
      catch (IllegalAccessException ex) {
        throw new PersistanceException(ex);
      }
    }
    return instance;
  }

  /**
   * Cria um DAO de cliente.
   */
  public abstract ClienteDAO createClienteDAO();

  /**
   * @Cria um DAO de pedido.
   */
  public abstract PedidoDAO createPedidoDAO();
}
