package persistence.dao;

import java.io.IOException;
import java.util.Properties;

import util.exception.ServiceException;

public final class DAOFactory {

	private static DAOFactory instance = new DAOFactory();
	private static final String DAO_PROPERTIES_FILE = "dao.properties";

    private DAOFactory() {
    }
  
    @SuppressWarnings("unchecked")
    public <T extends DAO> T getDao(Class<T> daoClass) throws ServiceException {
        final Properties daoProperties = this.getProperties();
        final String concreteClass = daoProperties.getProperty(daoClass.getName());
        
        if (concreteClass == null)
            throw new ServiceException("Erro recuperando classe concreta para a interface: " + daoClass.getName());
                
        try {
            final Class clazz = Class.forName(concreteClass);
            return (T) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            throw new ServiceException(e);
        } catch (IllegalAccessException e) {
            throw new ServiceException(e);
        } catch (InstantiationException e) {
            throw new ServiceException(e);
        }
        
    }

    private Properties getProperties() throws ServiceException {
		Properties p = new Properties();

		try {
			p.load(getClass().getClassLoader().getResourceAsStream(DAO_PROPERTIES_FILE));
		} catch (IOException e) {
            throw new ServiceException(e);
		}

        return p;
    }
	
    public static DAOFactory getInstance() {
        return instance;
    }

}
