/*
 * 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.metadata.datasource;

import com.google.common.base.Optional;
import io.shardingsphere.core.constant.DatabaseType;
import io.shardingsphere.core.rule.MasterSlaveRule;
import io.shardingsphere.core.rule.ShardingRule;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Sharding data source meta data.
 *
 * @author panjuan
 */
public class ShardingDataSourceMetaData {
    
    private final Map<String, DataSourceMetaData> dataSourceMetaDataMap;
    
    public ShardingDataSourceMetaData(final Map<String, String> dataSourceURLs, final ShardingRule shardingRule, final DatabaseType databaseType) {
        dataSourceMetaDataMap = getDataSourceMetaDataMap(dataSourceURLs, shardingRule, databaseType);
    }
    
    private Map<String, DataSourceMetaData> getDataSourceMetaDataMap(final Map<String, String> dataSourceURLs, final ShardingRule shardingRule, final DatabaseType databaseType) {
        Map<String, DataSourceMetaData> result = new LinkedHashMap<>(dataSourceURLs.size(), 1);
        for (Entry<String, String> entry : dataSourceURLs.entrySet()) {
            result.put(entry.getKey(), DataSourceMetaDataFactory.newInstance(databaseType, entry.getValue()));
        }
        handleMasterSlaveDataSources(shardingRule, result);
        return result;
    }
    
    private void handleMasterSlaveDataSources(final ShardingRule shardingRule, final Map<String, DataSourceMetaData> dataSourceMetaDataMap) {
        if (shardingRule.getMasterSlaveRules().isEmpty()) {
            return;
        }
        Collection<String> toRemovedKeys = new LinkedList<>();
        for (Entry<String, DataSourceMetaData> entry : dataSourceMetaDataMap.entrySet()) {
            final Optional<MasterSlaveRule> masterSlaveRule = shardingRule.findMasterSlaveRule(entry.getKey());
            if (masterSlaveRule.isPresent() && masterSlaveRule.get().getMasterDataSourceName().equals(entry.getKey())) {
                toRemovedKeys.add(masterSlaveRule.get().getMasterDataSourceName());
                toRemovedKeys.addAll(masterSlaveRule.get().getSlaveDataSourceNames());
                dataSourceMetaDataMap.put(masterSlaveRule.get().getName(), entry.getValue());
            }
        }
        removeDataSourceMetaData(dataSourceMetaDataMap, toRemovedKeys);
    }
    
    private void removeDataSourceMetaData(final Map<String, DataSourceMetaData> dataSourceMetaDataMap, final Collection<String> toRemovedKeys) {
        for (String each : toRemovedKeys) {
            dataSourceMetaDataMap.remove(each);
        }
    }
    
    /**
     * Get all instance data source names.
     *
     * @return instance data source names
     */
    public Collection<String> getAllInstanceDataSourceNames() {
        Collection<String> result = new LinkedList<>();
        for (Entry<String, DataSourceMetaData> entry : dataSourceMetaDataMap.entrySet()) {
            if (!isExisted(entry.getKey(), result)) {
                result.add(entry.getKey());
            }
        }
        return result;
    }
    
    private boolean isExisted(final String dataSourceName, final Collection<String> existedDataSourceNames) {
        for (String each : existedDataSourceNames) {
            if (dataSourceMetaDataMap.get(each).isInSameDatabaseInstance(dataSourceMetaDataMap.get(dataSourceName))) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * Get actual schema name.
     *
     * @param actualDataSourceName actual data source name
     * @return actual schema name
     */
    public String getActualSchemaName(final String actualDataSourceName) {
        return dataSourceMetaDataMap.get(actualDataSourceName).getSchemeName();
    }
}

@@ -2132,37 +2132,22 @@
 taData%3E 
-dataSourceMetaDataMap
+result
 ) %7B%0A    
@@ -2267,21 +2267,16 @@
 toRemove
-dKeys
  = new L
@@ -2294,34 +2294,27 @@
 ();%0A        
-for (Entry
+Map
 %3CString, Dat
@@ -2326,33 +2326,83 @@
 ceMetaData%3E 
-entry : d
+toAdd = new LinkedHashMap%3C%3E();%0A        for (Entry%3CString, D
 ataSourceMet
@@ -2398,35 +2398,48 @@
 taSourceMetaData
-Map
+%3E entry : result
 .entrySet()) %7B%0A 
@@ -2449,22 +2449,16 @@
         
-final 
 Optional
@@ -2684,29 +2684,24 @@
     toRemove
-dKeys
 .add(masterS
@@ -2767,21 +2767,16 @@
 toRemove
-dKeys
 .addAll(
@@ -2841,37 +2841,21 @@
         
-dataSourceMetaDataMap
+toAdd
 .put(mas
@@ -2937,24 +2937,31 @@
       remove
+Invalid
 DataSourceMe
@@ -2971,44 +2971,54 @@
 ata(
-dataSourceMetaDataMap, toRemovedKeys
+result, toRemove);%0A        result.putAll(toAdd
 );%0A 
@@ -3050,16 +3050,23 @@
 d remove
+Invalid
 DataSour
@@ -3114,37 +3114,22 @@
 taData%3E 
-dataSourceMetaDataMap
+result
 , final 
@@ -3220,37 +3220,22 @@
         
-dataSourceMetaDataMap
+result
 .remove(

rewrite handleMasterSlaveDataSources.