package org.seamframework.sql;

import java.lang.annotation.Annotation;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PreDestroy;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.sql.DataSource;

@RequestScoped
public class DefaultConnectionFactory implements ConnectionFactory {

	private @Inject @Any Instance<DataSource> connectionSource;
	private Map<Annotation, Connection> connections = new HashMap<Annotation, Connection>();
	
	@Override
	public Connection getConnection(Annotation qualifier) {
		Connection connection = connections.get(qualifier);
		if (connection==null) {
			DataSource dataSource = connectionSource.select(qualifier).get();
			try {
				connection = dataSource.getConnection();
			}
			catch (SQLException sqle) {
				throw new RuntimeException(sqle);
			}
			connections.put(qualifier, connection);
		}
		return connection;
	}

	@PreDestroy
	public void closeConnections() {
		for (Connection c: connections.values()) {
			try {
				 c.close();
			}
			catch (SQLException sqle) {
				//logger.warn(sqle);
			}
		}
	}
	
}
