package jp.sf.amateras.mirage.provider;

import java.sql.Connection;
import java.sql.SQLException;

import jp.sf.amateras.mirage.util.JdbcUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultConnectionProvider implements ConnectionProvider {

	private static final Logger logger = LoggerFactory.getLogger(DefaultConnectionProvider.class);

	private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

	public void setConnection(Connection conn){
		threadLocal.set(conn);
	}

	public void releaseConnection(){
		Connection conn = threadLocal.get();
		if(conn != null){
			JdbcUtil.close(conn);
			threadLocal.remove();

			if(logger.isDebugEnabled()){
				logger.debug("Connection is released.");
			}

		} else {
			if(logger.isDebugEnabled()){
				logger.debug("Connection is not used.");
			}
		}
	}

	@Override
	public Connection getConnection() throws SQLException {
		return threadLocal.get();
	}

}
