package net.savantly.sprout.tenancy;

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

import javax.sql.DataSource;

import org.hibernate.HibernateException;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;

import net.savantly.sprout.starter.SchemaConfiguration;

public class MultiTenantConnectionProviderImpl implements MultiTenantConnectionProvider {

	private DataSource dataSource;
	
	public MultiTenantConnectionProviderImpl(DataSource ds) {
		this.dataSource = ds;
	}
	
    @Override
    public Connection getAnyConnection() throws SQLException {
        return dataSource.getConnection();
    }
    @Override
    public void releaseAnyConnection(Connection connection) throws SQLException {
        connection.close();
    }
    @Override
    public Connection getConnection(String iy) throws SQLException {
        String tenantIdentifier = TenantContext.getCurrentTenant();
        final Connection connection = getAnyConnection();
        try {
            if (tenantIdentifier != null) {
                connection.createStatement().execute(String.format("USE %s", tenantIdentifier));
            } else {
            	connection.createStatement().execute(String.format("USE %s", SchemaConfiguration.DEFAULT_SCHEMA));
            }
        }
        catch ( SQLException e ) {
            throw new HibernateException(
                    "Problem setting schema to " + tenantIdentifier,
                    e
            );
        }
        return connection;
    }
    @Override
    public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
        connection.close();
    }
    @SuppressWarnings("rawtypes")
    @Override
    public boolean isUnwrappableAs(Class unwrapType) {
        return false;
    }
    @Override
    public <T> T unwrap(Class<T> unwrapType) {
        return null;
    }
    @Override
    public boolean supportsAggressiveRelease() {
        return true;
    }
}
@@ -1061,9 +1061,9 @@
 ier 
-!
+=
 = nu
@@ -1085,91 +1085,62 @@
     
-    connection.createStatement().execute(String.format(%22USE %25s%22, tenantIdentifier))
+%09tenantIdentifier = SchemaConfiguration.DEFAULT_SCHEMA
 ;%0D%0A 
@@ -1155,15 +1155,8 @@
    %7D
- else %7B
 %0D%0A  
@@ -1165,17 +1165,16 @@
         
-%09
 connecti
@@ -1230,60 +1230,27 @@
 s%22, 
-SchemaConfiguration.DEFAULT_SCHEMA));%0D%0A            %7D
+tenantIdentifier));
 %0D%0A  
@@ -1302,20 +1302,17 @@
         
-    
+%09
 throw ne

simplify statement