/*
 * 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.jdbc.orchestration.internal;

import com.google.common.eventbus.Subscribe;
import io.shardingsphere.core.api.config.ShardingRuleConfiguration;
import io.shardingsphere.core.constant.properties.ShardingProperties;
import io.shardingsphere.core.event.orche.config.ShardingConfigurationEventBusEvent;
import io.shardingsphere.core.event.orche.state.CircuitStateEventBusEvent;
import io.shardingsphere.core.event.orche.state.DisabledStateEventBusEvent;
import io.shardingsphere.core.jdbc.adapter.AbstractDataSourceAdapter;
import io.shardingsphere.core.jdbc.core.connection.ShardingConnection;
import io.shardingsphere.core.jdbc.core.datasource.ShardingDataSource;
import io.shardingsphere.core.orche.datasource.CircuitBreakerDataSource;
import io.shardingsphere.core.rule.ShardingRule;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;

/**
 * Orchestration sharding datasource.
 *
 * @author caohao
 */
@Slf4j
public final class OrchestrationShardingDataSource extends AbstractDataSourceAdapter implements AutoCloseable {
    
    private final ShardingDataSource dataSource;
    
    private final OrchestrationFacade orchestrationFacade;
    
    private Collection<String> disabledDataSourceNames = new LinkedList<>();
    
    private boolean isCircuitBreak;
    
    public OrchestrationShardingDataSource(final Map<String, DataSource> dataSourceMap, final ShardingRuleConfiguration shardingRuleConfig,
                                           final Map<String, Object> configMap, final Properties props, final OrchestrationFacade orchestrationFacade) throws SQLException {
        super(dataSourceMap.values());
        this.dataSource = new ShardingDataSource(dataSourceMap, new ShardingRule(shardingRuleConfig, dataSourceMap.keySet()), configMap, props);
        this.orchestrationFacade = orchestrationFacade;
        this.orchestrationFacade.init(dataSourceMap, shardingRuleConfig, configMap, props);
    }
    
    @Override
    public ShardingConnection getConnection() {
        return dataSource.getConnection();
    }
    
    @Override
    public void close() {
        dataSource.close();
        orchestrationFacade.close();
    }
    
//    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 ShardingRuleConfiguration getShardingRuleConfiguration(final Map<String, DataSource> dataSourceMap, final ShardingRuleConfiguration shardingRuleConfig) {
//        Collection<MasterSlaveRuleConfiguration> masterSlaveRuleConfigs = new LinkedList<>();
//        if (null == dataSourceMap || !shardingRuleConfig.getMasterSlaveRuleConfigs().isEmpty()) {
//            return shardingRuleConfig;
//        }
//        for (DataSource each : dataSourceMap.values()) {
//            if (!(each instanceof MasterSlaveDataSource)) {
//                continue;
//            }
//            MasterSlaveRule masterSlaveRule = ((MasterSlaveDataSource) each).getMasterSlaveRule();
//            masterSlaveRuleConfigs.add(new MasterSlaveRuleConfiguration(
//                    masterSlaveRule.getName(), masterSlaveRule.getMasterDataSourceName(), masterSlaveRule.getSlaveDataSourceNames(), masterSlaveRule.getLoadBalanceAlgorithm()));
//        }
//        shardingRuleConfig.setMasterSlaveRuleConfigs(masterSlaveRuleConfigs);
//        return shardingRuleConfig;
//    }
    
    /**
     * Renew disable dataSource names.
     *
     * @param disabledStateEventBusEvent jdbc disabled event bus event
     */
    @Subscribe
    public void renewDisabledDataSourceNames(final DisabledStateEventBusEvent disabledStateEventBusEvent) {
        disabledDataSourceNames = disabledStateEventBusEvent.getDisabledDataSourceNames();
    }
    
    /**
     * Renew circuit breaker dataSource names.
     *
     * @param circuitStateEventBusEvent jdbc disabled event bus event
     */
    @Subscribe
    public void renewCircuitBreakerDataSourceNames(final CircuitStateEventBusEvent circuitStateEventBusEvent) {
        isCircuitBreak = circuitStateEventBusEvent.isCircuitBreak();
    }
    
    /**
     * Get available data source map.
     *
     * @return available data source map
     */
    public Map<String, DataSource> getDataSourceMap() {
        if (isCircuitBreak) {
            return getCircuitBreakerDataSourceMap();
        }
        if (!disabledDataSourceNames.isEmpty()) {
            return getAvailableDataSourceMap();
        }
        return dataSource.getDataSourceMap();
    }
    
    private Map<String, DataSource> getAvailableDataSourceMap() {
        Map<String, DataSource> result = new LinkedHashMap<>(dataSource.getDataSourceMap());
        for (String each : disabledDataSourceNames) {
            result.remove(each);
        }
        return result;
    }
    
    private Map<String, DataSource> getCircuitBreakerDataSourceMap() {
        Map<String, DataSource> result = new LinkedHashMap<>();
        for (String each : dataSource.getDataSourceMap().keySet()) {
            result.put(each, new CircuitBreakerDataSource());
        }
        return result;
    }
    
    /**
     * Renew sharding data source.
     *
     * @param shardingEvent sharding configuration event bus event.
     */
    @Subscribe
    public void renew(final ShardingConfigurationEventBusEvent shardingEvent) {
        super.renew(shardingEvent.getDataSourceMap().values());
        ShardingProperties shardingProperties = new ShardingProperties(null == shardingEvent.getProps() ? new Properties() : shardingEvent.getProps());
        dataSource.renew(shardingEvent.getDataSourceMap(), shardingEvent.getShardingRule(), shardingProperties);
    }
}

@@ -1304,81 +1304,8 @@
 ce;%0A
-import io.shardingsphere.core.orche.datasource.CircuitBreakerDataSource;%0A
 impo
@@ -1349,16 +1349,16 @@
 ngRule;%0A
+
 import l
@@ -1447,98 +1447,8 @@
 on;%0A
-import java.util.Collection;%0Aimport java.util.LinkedHashMap;%0Aimport java.util.LinkedList;%0A
 impo
@@ -1732,32 +1732,32 @@
 ataSource;%0A    %0A
+
     private fina
@@ -1808,131 +1808,8 @@
    %0A
-    private Collection%3CString%3E disabledDataSourceNames = new LinkedList%3C%3E();%0A    %0A    private boolean isCircuitBreak;%0A    %0A
     
@@ -4780,16 +4780,32 @@
        d
+ataSource.renewD
 isabledD
@@ -4818,19 +4818,17 @@
 rceNames
- = 
+(
 disabled
@@ -4874,16 +4874,17 @@
 eNames()
+)
 ;%0A    %7D%0A
@@ -5167,1083 +5167,97 @@
     
-isCircuitBreak = circuitStateEventBusEvent.isCircuitBreak();%0A    %7D%0A    %0A    /**%0A     * Get available 
 data
- s
+S
 ource
- map.%0A     *%0A     * @return available data source map%0A     */%0A    public Map%3CString, DataSource%3E getDataSourceMap() %7B%0A        if (isCircuitBreak) %7B%0A            return getCircuitBreakerDataSourceMap();%0A        %7D%0A        if (!disabledDataSourceNames.isEmpty()) %7B%0A            return getAvailableDataSourceMap();%0A        %7D%0A        return dataSource.getDataSourceMap();%0A    %7D%0A    %0A    private Map%3CString, DataSource%3E getAvailableDataSourceMap() %7B%0A        Map%3CString, DataSource%3E result = new LinkedHashMap%3C%3E(dataSource.getDataSourceMap());%0A        for (String each : disabledDataSourceNames) %7B%0A            result.remove(each);%0A        %7D%0A        return result;%0A    %7D%0A    %0A    private Map%3CString, DataSource%3E getCircuitBreakerDataSourceMap() %7B%0A        Map%3CString, DataSource%3E result = new LinkedHashMap%3C%3E();%0A        for (String each : dataSource.getDataSourceMap().keySet()) %7B%0A            result.put(each, new CircuitBreakerDataSource());%0A        %7D%0A        return result
+.renewCircuitBreakerDataSourceNames(circuitStateEventBusEvent.isCircuitBreak())
 ;%0A  

rewrite renewDisabledDataSourceNames