/*
 * 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.proxy.config;

import com.google.common.base.Preconditions;
import org.apache.shardingsphere.proxy.config.yaml.YamlDataSourceParameterMerger;
import org.apache.shardingsphere.proxy.config.yaml.YamlProxyRuleConfiguration;
import org.apache.shardingsphere.proxy.config.yaml.YamlProxyServerConfiguration;
import org.apache.shardingsphere.infra.yaml.engine.YamlEngine;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Sharding configuration loader.
 */
public final class ShardingConfigurationLoader {
    
    private static final String DEFAULT_DATASOURCE_NAME = "dataSource";
    
    private static final String SERVER_CONFIG_FILE = "server.yaml";
    
    private static final Pattern RULE_CONFIG_FILE_PATTERN = Pattern.compile("config-.+\\.yaml");
    
    /**
     * Load configuration of ShardingSphere-Proxy.
     *
     * @param path configuration path of ShardingSphere-Proxy
     * @return configuration of ShardingSphere-Proxy
     * @throws IOException IO exception
     */
    public ShardingConfiguration load(final String path) throws IOException {
        Collection<String> schemaNames = new HashSet<>();
        YamlProxyServerConfiguration serverConfig = loadServerConfiguration(new File(ShardingConfigurationLoader.class.getResource(path + "/" + SERVER_CONFIG_FILE).getFile()));
        File configPath = new File(ShardingConfigurationLoader.class.getResource(path).getFile());
        Collection<YamlProxyRuleConfiguration> ruleConfigurations = new LinkedList<>();
        for (File each : findRuleConfigurationFiles(configPath)) {
            loadRuleConfiguration(each).ifPresent(yamlProxyRuleConfiguration -> {
                Preconditions.checkState(
                        schemaNames.add(yamlProxyRuleConfiguration.getSchemaName()), "Schema name `%s` must unique at all rule configurations.", yamlProxyRuleConfiguration.getSchemaName());
                ruleConfigurations.add(yamlProxyRuleConfiguration);
            });
        }
        Preconditions.checkState(!ruleConfigurations.isEmpty() || null != serverConfig.getOrchestration(), "Can not find any sharding rule configuration file in path `%s`.", configPath.getPath());
        Map<String, YamlProxyRuleConfiguration> ruleConfigurationMap = ruleConfigurations.stream().collect(Collectors.toMap(YamlProxyRuleConfiguration::getSchemaName, each -> each));
        return new ShardingConfiguration(serverConfig, ruleConfigurationMap);
    }
    
    private YamlProxyServerConfiguration loadServerConfiguration(final File yamlFile) throws IOException {
        YamlProxyServerConfiguration result = YamlEngine.unmarshal(yamlFile, YamlProxyServerConfiguration.class);
        Preconditions.checkNotNull(result, "Server configuration file `%s` is invalid.", yamlFile.getName());
        Preconditions.checkState(null != result.getAuthentication() || null != result.getOrchestration(), "Authority configuration is invalid.");
        return result;
    }
    
    private Optional<YamlProxyRuleConfiguration> loadRuleConfiguration(final File yamlFile) throws IOException {
        YamlProxyRuleConfiguration result = YamlEngine.unmarshal(yamlFile, YamlProxyRuleConfiguration.class);
        if (null == result) {
            return Optional.empty();
        }
        Preconditions.checkNotNull(result.getSchemaName(), "Property `schemaName` in file `%s` is required.", yamlFile.getName());
        result.getDataSources().forEach((dataSourceName, dataSourceParameter) -> YamlDataSourceParameterMerger.merged(dataSourceParameter, result.getDataSourceCommon()));
        if (result.getDataSources().isEmpty() && null != result.getDataSource()) {
            YamlDataSourceParameterMerger.merged(result.getDataSource(), result.getDataSourceCommon());
            result.getDataSources().put(DEFAULT_DATASOURCE_NAME, result.getDataSource());
        }
        Preconditions.checkState(!result.getDataSources().isEmpty(), "Data sources configuration in file `%s` is required.", yamlFile.getName());
        return Optional.of(result);
    }
    
    private File[] findRuleConfigurationFiles(final File path) {
        return path.listFiles(pathname -> RULE_CONFIG_FILE_PATTERN.matcher(pathname.getName()).matches());
    }
}

@@ -1241,24 +1241,45 @@
 OException;%0A
+import java.net.URL;%0A
 import java.
@@ -1291,24 +1291,24 @@
 Collection;%0A
-
 import java.
@@ -2115,32 +2115,88 @@
 s IOException %7B%0A
+        //this is just check for schemaName duplication%0A
         Collecti
@@ -2317,51 +2317,8 @@
 ion(
-new File(ShardingConfigurationLoader.class.
 getR
@@ -2320,24 +2320,28 @@
 (getResource
+File
 (path + %22/%22 
@@ -2361,27 +2361,16 @@
 IG_FILE)
-.getFile())
 );%0A     
@@ -2394,51 +2394,8 @@
 h = 
-new File(ShardingConfigurationLoader.class.
 getR
@@ -2405,25 +2405,18 @@
 urce
+File
 (path)
-.getFile())
 ;%0A  
@@ -3352,24 +3352,24 @@
  -%3E each));%0A
-
         retu
@@ -3437,32 +3437,308 @@
 ap);%0A    %7D%0A    %0A
+    private File getResourceFile(final String path) %7B%0A        URL url = ShardingConfigurationLoader.class.getResource(path);%0A        if (url != null) %7B%0A            return new File(url.getFile());%0A        %7D%0A        //try absolute path%0A        return new File(path);%0A    %7D%0A    %0A
     private Yaml

support load absolute path