/*
 * 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.ConfigMapContext;
import io.shardingsphere.core.api.config.MasterSlaveRuleConfiguration;
import io.shardingsphere.core.event.orche.config.MasterSlaveConfigurationEventBusEvent;
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.MasterSlaveConnection;
import io.shardingsphere.core.jdbc.core.datasource.MasterSlaveDataSource;
import io.shardingsphere.core.orche.datasource.CircuitBreakerDataSource;
import lombok.Getter;
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 master-slave datasource.
 *
 * @author caohao
 * @author panjuan
 */
@Slf4j
public final class OrchestrationMasterSlaveDataSource extends AbstractDataSourceAdapter implements AutoCloseable {
    
    @Getter
    private MasterSlaveDataSource dataSource;
    
    private final OrchestrationFacade orchestrationFacade;
    
    private Collection<String> disabledDataSourceNames = new LinkedList<>();
    
    private boolean isCircuitBreak;
    
    public OrchestrationMasterSlaveDataSource(final Map<String, DataSource> dataSourceMap, final MasterSlaveRuleConfiguration masterSlaveRuleConfig,
                                              final Map<String, Object> configMap, final Properties props, final OrchestrationFacade orchestrationFacade) throws SQLException {
        super(getAllDataSources(dataSourceMap, masterSlaveRuleConfig.getMasterDataSourceName(), masterSlaveRuleConfig.getSlaveDataSourceNames()));
        this.dataSource = new MasterSlaveDataSource(dataSourceMap, masterSlaveRuleConfig, configMap, props);
        this.orchestrationFacade = orchestrationFacade;
        this.orchestrationFacade.init(dataSourceMap, masterSlaveRuleConfig, configMap, props);
    }
    
    private static Collection<DataSource> getAllDataSources(final Map<String, DataSource> dataSourceMap, final String masterDataSourceName, final Collection<String> slaveDataSourceNames) {
        Collection<DataSource> result = new LinkedList<>();
        result.add(dataSourceMap.get(masterDataSourceName));
        for (String each : slaveDataSourceNames) {
            result.add(dataSourceMap.get(each));
        }
        return result;
    }
    
    @Override
    public MasterSlaveConnection getConnection() {
        return dataSource.getConnection();
    }
    
    @Override
    public void close() {
        dataSource.close();
        orchestrationFacade.close();
    }
    
    /**
     * Renew master-slave data source.
     *
     * @param masterSlaveEvent master slave configuration event bus event
     * @throws SQLException sql exception
     */
    @Subscribe
    public void renew(final MasterSlaveConfigurationEventBusEvent masterSlaveEvent) throws SQLException {
        this.dataSource.close();
        this.dataSource = new MasterSlaveDataSource(masterSlaveEvent.getDataSourceMap(), masterSlaveEvent.getMasterSlaveRuleConfig(), ConfigMapContext.getInstance().getMasterSlaveConfig(), masterSlaveEvent.getProps());
        MasterSlaveRuleConfiguration masterSlaveRuleConfig = masterSlaveEvent.getMasterSlaveRuleConfig();
        super.renew(getAllDataSources(masterSlaveEvent.getDataSourceMap(), masterSlaveRuleConfig.getMasterDataSourceName(), masterSlaveRuleConfig.getSlaveDataSourceNames()));
    }
    
    /**
     * 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 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 circuit event bus event
     */
    @Subscribe
    public void renewCircuitBreakerDataSourceNames(final CircuitStateEventBusEvent circuitStateEventBusEvent) {
        isCircuitBreak = circuitStateEventBusEvent.isCircuitBreak();
    }
    
    /**
     * Show SQL or not.
     *
     * @return show SQL or not
     */
    public boolean showSQL() {
        return dataSource.showSQL();
    }
}

@@ -1298,103 +1298,8 @@
 ce;%0A
-import io.shardingsphere.core.orche.datasource.CircuitBreakerDataSource;%0Aimport lombok.Getter;%0A
 impo
@@ -1328,16 +1328,16 @@
 .Slf4j;%0A
+
 %0Aimport 
@@ -1421,40 +1421,8 @@
 on;%0A
-import java.util.LinkedHashMap;%0A
 impo
@@ -1719,20 +1719,8 @@
    %0A
-    @Getter%0A
     
@@ -1834,131 +1834,8 @@
    %0A
-    private Collection%3CString%3E disabledDataSourceNames = new LinkedList%3C%3E();%0A    %0A    private boolean isCircuitBreak;%0A    %0A
     
@@ -3565,260 +3565,8 @@
 n %7B%0A
-        this.dataSource.close();%0A        this.dataSource = new MasterSlaveDataSource(masterSlaveEvent.getDataSourceMap(), masterSlaveEvent.getMasterSlaveRuleConfig(), ConfigMapContext.getInstance().getMasterSlaveConfig(), masterSlaveEvent.getProps());%0A
     
@@ -3850,1027 +3850,244 @@
     
-%7D%0A
     
-%0A    /**%0A     * Get available 
 data
- s
+S
 ource
- map.
+.close();
 %0A     
-*%0A
    
-  * @return available 
 data
- s
+S
 ource 
-map%0A     */%0A    public Map%3CString, DataSource%3E getDataSourceMap() %7B%0A        if (isCircuitBreak) %7B%0A            return getCircuitBreakerDataSourceMap();%0A        %7D%0A        %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
+= new MasterSlaveDataSource(masterSlaveEvent.getDataSourceMap(), masterSlaveEvent.getMasterSlaveRuleConfig(), ConfigMapContext.getInstance().getMasterSlaveConfig(), masterSlaveEvent.getProps())
 ;%0A  
@@ -4360,16 +4360,32 @@
        d
+ataSource.renewD
 isabledD
@@ -4398,19 +4398,17 @@
 rceNames
- = 
+(
 disabled
@@ -4454,16 +4454,17 @@
 eNames()
+)
 ;%0A    %7D%0A
@@ -4746,25 +4746,54 @@
     
-isCircuitBreak = 
+dataSource.renewCircuitBreakerDataSourceNames(
 circ
@@ -4830,16 +4830,17 @@
 tBreak()
+)
 ;%0A    %7D%0A

rewrite renewDisabledDataSourceNames