/*
 * Copyright 2016-2018 shardingsphere.io.
 * <p>
 * Licensed 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.
 * </p>
 */

package io.shardingsphere.core.jdbc.core.datasource;

import io.shardingsphere.core.api.ConfigMapContext;
import io.shardingsphere.core.api.config.MasterSlaveRuleConfiguration;
import io.shardingsphere.core.api.config.ShardingRuleConfiguration;
import io.shardingsphere.core.constant.ConnectionMode;
import io.shardingsphere.core.constant.DatabaseType;
import io.shardingsphere.core.constant.properties.ShardingProperties;
import io.shardingsphere.core.constant.properties.ShardingPropertiesConstant;
import io.shardingsphere.core.executor.ShardingExecuteEngine;
import io.shardingsphere.core.jdbc.adapter.AbstractDataSourceAdapter;
import io.shardingsphere.core.jdbc.core.ShardingContext;
import io.shardingsphere.core.jdbc.core.connection.ShardingConnection;
import io.shardingsphere.core.rule.MasterSlaveRule;
import io.shardingsphere.core.rule.ShardingRule;
import lombok.Getter;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Database that support sharding.
 *
 * @author zhangliang
 * @author zhaojun
 * @author panjuan
 */
@Getter
public class ShardingDataSource extends AbstractDataSourceAdapter implements AutoCloseable {
    
    private final Map<String, DataSource> dataSourceMap;
    
    private final ShardingContext shardingContext;
    
    private final ShardingProperties shardingProperties;
    
    public ShardingDataSource(final Map<String, DataSource> dataSourceMap, final ShardingRule shardingRule) throws SQLException {
        this(dataSourceMap, shardingRule, new ConcurrentHashMap<String, Object>(), new Properties());
    }
    
    public ShardingDataSource(final Map<String, DataSource> dataSourceMap, final ShardingRule shardingRule, final Map<String, Object> configMap, final Properties props) throws SQLException {
        super(dataSourceMap.values());
        if (!configMap.isEmpty()) {
            ConfigMapContext.getInstance().getShardingConfig().putAll(configMap);
        }
        this.dataSourceMap = getRawDataSourceMap(dataSourceMap);
        this.shardingProperties = new ShardingProperties(null == props ? new Properties() : props);
        this.shardingContext = getShardingContext(getRawDataSourceMap(dataSourceMap), getRevisedShardingRule(dataSourceMap, shardingRule));
    }
    
    public ShardingDataSource(final Map<String, DataSource> dataSourceMap, final ShardingContext shardingContext, final ShardingProperties shardingProperties, final DatabaseType databaseType) {
        super(databaseType);
        this.dataSourceMap = getRawDataSourceMap(dataSourceMap);
        this.shardingContext = shardingContext;
        this.shardingProperties = shardingProperties;
    }
    
    private ShardingContext getShardingContext(final Map<String, DataSource> dataSourceMap, final ShardingRule shardingRule) {
        boolean showSQL = shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW);
        int executorSize = shardingProperties.getValue(ShardingPropertiesConstant.EXECUTOR_SIZE);
        ShardingExecuteEngine executeEngine = new ShardingExecuteEngine(executorSize);
        ConnectionMode connectionMode = ConnectionMode.valueOf(shardingProperties.<String>getValue(ShardingPropertiesConstant.CONNECTION_MODE));
        int maxConnectionsSizePerQuery = shardingProperties.getValue(ShardingPropertiesConstant.MAX_CONNECTIONS_SIZE_PER_QUERY);
        return new ShardingContext(dataSourceMap, shardingRule, getDatabaseType(), executeEngine, connectionMode, maxConnectionsSizePerQuery, showSQL);
    }
    
    private Map<String, DataSource> getRawDataSourceMap(final Map<String, DataSource> dataSourceMap) {
        Map<String, DataSource> result = new LinkedHashMap<>();
        if (null == dataSourceMap) {
            return result;
        }
        for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
            String dataSourceName = entry.getKey();
            DataSource dataSource = entry.getValue();
            if (dataSource instanceof MasterSlaveDataSource) {
                result.putAll(((MasterSlaveDataSource) dataSource).getAllDataSources());
            } else {
                result.put(dataSourceName, dataSource);
            }
        }
        return result;
    }
    
    private ShardingRule getRevisedShardingRule(final Map<String, DataSource> dataSourceMap, final ShardingRule shardingRule) {
        if (null == dataSourceMap || !shardingRule.getMasterSlaveRules().isEmpty()) {
            return shardingRule;
        }
        ShardingRuleConfiguration shardingRuleConfiguration = shardingRule.getShardingRuleConfig();
        for (DataSource each : dataSourceMap.values()) {
            if (!(each instanceof MasterSlaveDataSource)) {
                continue;
            }
            MasterSlaveRule masterSlaveRule = ((MasterSlaveDataSource) each).getMasterSlaveRule();
            shardingRuleConfiguration.getMasterSlaveRuleConfigs().add(new MasterSlaveRuleConfiguration(
                    masterSlaveRule.getName(), masterSlaveRule.getMasterDataSourceName(), masterSlaveRule.getSlaveDataSourceNames(), masterSlaveRule.getLoadBalanceAlgorithm()));
        }
        return new ShardingRule(shardingRuleConfiguration, dataSourceMap.keySet());
    }
    
    @Override
    public final ShardingConnection getConnection() {
        return new ShardingConnection(this);
    }
    
    @Override
    public void close() {
        closeOriginalDataSources();
        shardingContext.close();
    }
    
    private void closeOriginalDataSources() {
        for (DataSource each : dataSourceMap.values()) {
            try {
                each.getClass().getDeclaredMethod("close").invoke(each);
            } catch (final ReflectiveOperationException ignored) {
            }
        }
    }
}

@@ -723,147 +723,8 @@
 xt;%0A
-import io.shardingsphere.core.api.config.MasterSlaveRuleConfiguration;%0Aimport io.shardingsphere.core.api.config.ShardingRuleConfiguration;%0A
 impo
@@ -774,16 +774,16 @@
 onMode;%0A
+
 import i
@@ -1239,60 +1239,8 @@
 on;%0A
-import io.shardingsphere.core.rule.MasterSlaveRule;%0A
 impo
@@ -1370,40 +1370,8 @@
 on;%0A
-import java.util.LinkedHashMap;%0A
 impo
@@ -2487,36 +2487,16 @@
 ceMap = 
-getRawDataSourceMap(
 dataSour
@@ -2492,33 +2492,32 @@
  = dataSourceMap
-)
 ;%0A        this.s
@@ -2656,67 +2656,8 @@
 ext(
-getRawDataSourceMap(dataSourceMap), getRevisedShardingRule(
 data
@@ -2680,17 +2680,16 @@
 ingRule)
-)
 ;%0A    %7D%0A
@@ -2945,36 +2945,16 @@
 ceMap = 
-getRawDataSourceMap(
 dataSour
@@ -2958,17 +2958,16 @@
 ourceMap
-)
 ;%0A      
@@ -3751,16 +3751,16 @@
 QUERY);%0A
+
         
@@ -3918,1721 +3918,8 @@
    %0A
-    private Map%3CString, DataSource%3E getRawDataSourceMap(final Map%3CString, DataSource%3E dataSourceMap) %7B%0A        Map%3CString, DataSource%3E result = new LinkedHashMap%3C%3E();%0A        if (null == dataSourceMap) %7B%0A            return result;%0A        %7D%0A        for (Map.Entry%3CString, DataSource%3E entry : dataSourceMap.entrySet()) %7B%0A            String dataSourceName = entry.getKey();%0A            DataSource dataSource = entry.getValue();%0A            if (dataSource instanceof MasterSlaveDataSource) %7B%0A                result.putAll(((MasterSlaveDataSource) dataSource).getAllDataSources());%0A            %7D else %7B%0A                result.put(dataSourceName, dataSource);%0A            %7D%0A        %7D%0A        return result;%0A    %7D%0A    %0A    private ShardingRule getRevisedShardingRule(final Map%3CString, DataSource%3E dataSourceMap, final ShardingRule shardingRule) %7B%0A        if (null == dataSourceMap %7C%7C !shardingRule.getMasterSlaveRules().isEmpty()) %7B%0A            return shardingRule;%0A        %7D%0A        ShardingRuleConfiguration shardingRuleConfiguration = shardingRule.getShardingRuleConfig();%0A        for (DataSource each : dataSourceMap.values()) %7B%0A            if (!(each instanceof MasterSlaveDataSource)) %7B%0A                continue;%0A            %7D%0A            MasterSlaveRule masterSlaveRule = ((MasterSlaveDataSource) each).getMasterSlaveRule();%0A            shardingRuleConfiguration.getMasterSlaveRuleConfigs().add(new MasterSlaveRuleConfiguration(%0A                    masterSlaveRule.getName(), masterSlaveRule.getMasterDataSourceName(), masterSlaveRule.getSlaveDataSourceNames(), masterSlaveRule.getLoadBalanceAlgorithm()));%0A        %7D%0A        return new ShardingRule(shardingRuleConfiguration, dataSourceMap.keySet());%0A    %7D%0A    %0A
     

delete getRawDataSourceMap