/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.shardingsphere.shardingjdbc.jdbc.adapter;

import com.google.common.base.Preconditions;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.core.constant.DatabaseType;
import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationDataSource;
import org.apache.shardingsphere.transaction.ShardingTransactionManagerEngine;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Adapter for {@code Datasource}.
 * 
 * @author zhangliang
 * @author panjuan
 * @author zhaojun
 */
@Getter
@Setter
public abstract class AbstractDataSourceAdapter extends AbstractUnsupportedOperationDataSource implements AutoCloseable {
    
    private final DatabaseType databaseType;
    
    private final Map<String, DataSource> dataSourceMap;
    
    private ShardingTransactionManagerEngine shardingTransactionManagerEngine = new ShardingTransactionManagerEngine();
    
    private PrintWriter logWriter = new PrintWriter(System.out);
    
    public AbstractDataSourceAdapter(final Map<String, DataSource> dataSourceMap) throws SQLException {
        databaseType = getDatabaseType(dataSourceMap.values());
        shardingTransactionManagerEngine.init(databaseType, dataSourceMap);
        this.dataSourceMap = dataSourceMap;
    }
    
    protected final DatabaseType getDatabaseType(final Collection<DataSource> dataSources) throws SQLException {
        DatabaseType result = null;
        for (DataSource each : dataSources) {
            DatabaseType databaseType = getDatabaseType(each);
            Preconditions.checkState(null == result || result.equals(databaseType), String.format("Database type inconsistent with '%s' and '%s'", result, databaseType));
            result = databaseType;
        }
        return result;
    }
    
    private DatabaseType getDatabaseType(final DataSource dataSource) throws SQLException {
        if (dataSource instanceof AbstractDataSourceAdapter) {
            return ((AbstractDataSourceAdapter) dataSource).databaseType;
        }
        try (Connection connection = dataSource.getConnection()) {
            return DatabaseType.valueFrom(connection.getMetaData().getDatabaseProductName());
        }
    }
    
    @Override
    public final Logger getParentLogger() {
        return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    }
    
    @Override
    public final Connection getConnection(final String username, final String password) throws SQLException {
        return getConnection();
    }
    
    @Override
    public void close() throws Exception {
        for (DataSource each : dataSourceMap.values()) {
            try {
                Method method = each.getClass().getDeclaredMethod("close");
                method.setAccessible(true);
                method.invoke(each);
            } catch (final ReflectiveOperationException ignored) {
            }
        }
        shardingTransactionManagerEngine.close();
    }
}

@@ -3574,72 +3574,478 @@
     
-for (DataSource each : dataSourceMap.values()) %7B
+close(dataSourceMap.keySet());%0A    %7D%0A    %0A    /**%0A     * Close dataSources.%0A     * %0A     * @param dataSourceNames data source names%0A     * @throws Exception exception%0A     */%0A    public void close(final Collection%3CString%3E dataSourceNames) throws Exception %7B%0A        for (String each : dataSourceNames) %7B%0A            close(dataSourceMap.get(each));%0A        %7D%0A        shardingTransactionManagerEngine.close();%0A    %7D
 %0A    
+%0A
     
-    try
+private void close(final DataSource dataSource)
  %7B%0A 
@@ -4042,32 +4042,39 @@
 ource) %7B%0A       
+ try %7B%0A
          Method 
@@ -4066,16 +4066,19 @@
         
+   
 Method m
@@ -4085,20 +4085,26 @@
 ethod = 
-each
+dataSource
 .getClas
@@ -4135,20 +4135,16 @@
 lose%22);%0A
-    
         
@@ -4183,28 +4183,24 @@
             
-    
 method.invok
@@ -4201,20 +4201,26 @@
 .invoke(
-each
+dataSource
 );%0A     
@@ -4222,20 +4222,16 @@
         
-  
-  
 %7D catch 
@@ -4289,73 +4289,9 @@
     
-    %7D%0A        %7D%0A        shardingTransactionManagerEngine.close();
+%7D
 %0A   

modify close()