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

import com.google.common.base.Preconditions;
import io.shardingsphere.core.util.EventBusInstance;
import io.shardingsphere.jdbc.orchestration.internal.OrchestrationFacade;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.ProxyEventBusInstance;
import io.shardingsphere.proxy.config.RuleRegistry;
import io.shardingsphere.proxy.frontend.ShardingProxy;
import io.shardingsphere.proxy.yaml.YamlProxyConfiguration;
import io.shardingsphere.transaction.xa.XaTransactionListener;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;

/**
 * Sharding-Proxy Bootstrap.
 *
 * @author zhangliang
 * @author wangkai
 * @author panjuan
 */
public final class Bootstrap {
    
    private static final int DEFAULT_PORT = 3307;
    
    private static final String CONFIG_YAML = "/conf/config.yaml";
    
    /**
     * Main Entrance.
     * 
     * @param args startup arguments
     * @throws InterruptedException interrupted exception
     * @throws IOException IO exception
     */
    public static void main(final String[] args) throws InterruptedException, IOException {
        YamlProxyConfiguration localConfig = loadLocalConfiguration(new File(Bootstrap.class.getResource(CONFIG_YAML).getFile()));
        if (null == localConfig.getOrchestration()) {
            startWithoutRegistryCenter(localConfig, args);
        } else {
            startWithRegistryCenter(localConfig, args);
        }
    }
    
    private static YamlProxyConfiguration loadLocalConfiguration(final File yamlFile) throws IOException {
        try (
                FileInputStream fileInputStream = new FileInputStream(yamlFile);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8")
        ) {
            YamlProxyConfiguration result = new Yaml(new Constructor(YamlProxyConfiguration.class)).loadAs(inputStreamReader, YamlProxyConfiguration.class);
            Preconditions.checkNotNull(result, String.format("Configuration file `%s` is invalid.", CONFIG_YAML));
            return result;
        }
    }
    
    private static void startWithoutRegistryCenter(final YamlProxyConfiguration config, final String[] args) throws InterruptedException, MalformedURLException {
        RuleRegistry.getInstance().init(config);
        EventBusInstance.getInstance().register(new XaTransactionListener());
        new ShardingProxy().start(getPort(args));
    }
    
    private static void startWithRegistryCenter(final YamlProxyConfiguration localConfig, final String[] args) throws InterruptedException, MalformedURLException {
        try (OrchestrationFacade orchestrationFacade = new OrchestrationFacade(localConfig.getOrchestration().getOrchestrationConfiguration())) {
            YamlProxyConfiguration config = localConfig.isEmptyLocalConfiguration()
                    ? new YamlProxyConfiguration(orchestrationFacade.getConfigService().loadDataSources(), orchestrationFacade.getConfigService().loadProxyConfiguration()) : localConfig;
            orchestrationFacade.init(config);
            RuleRegistry.getInstance().init(config);
            ProxyEventBusInstance.getInstance().register(new YamlProxyConfiguration());
            EventBusInstance.getInstance().register(new XaTransactionListener());
            new ShardingProxy().start(getPort(args));    
        }
    }
    
    private static int getPort(final String[] args) {
        if (0 == args.length) {
            return DEFAULT_PORT;
        }
        try {
            return Integer.parseInt(args[0]);
        } catch (final NumberFormatException ex) {
            return DEFAULT_PORT;
        }
    }
}

@@ -2036,24 +2036,58 @@
 etFile()));%0A
+        int port = getPort(args);%0A
         if (
@@ -2172,36 +2172,36 @@
 er(localConfig, 
-args
+port
 );%0A        %7D els
@@ -2253,20 +2253,20 @@
 Config, 
-args
+port
 );%0A     
@@ -2909,32 +2909,326 @@
    %7D%0A    %7D%0A    %0A
+    private static int getPort(final String%5B%5D args) %7B%0A        if (0 == args.length) %7B%0A            return DEFAULT_PORT;%0A        %7D%0A        try %7B%0A            return Integer.parseInt(args%5B0%5D);%0A        %7D catch (final NumberFormatException ex) %7B%0A            return DEFAULT_PORT;%0A        %7D%0A    %7D%0A    %0A
     private stat
@@ -3301,37 +3301,32 @@
 nfig, final 
-String%5B%5D args
+int port
 ) throws Int
@@ -3529,29 +3529,20 @@
 ).start(
-getPort(args)
+port
 );%0A    %7D
@@ -3639,37 +3639,32 @@
 nfig, final 
-String%5B%5D args
+int port
 ) throws Int
@@ -3900,233 +3900,67 @@
 g = 
-localConfig.isEmptyLocalConfiguration()%0A                    ? new YamlProxyConfiguration(orchestrationFacade.getConfigService().loadDataSources(), orchestrationFacade.getConfigService().loadProxyConfiguration()) : localConfig
+getYamlProxyConfiguration(localConfig, orchestrationFacade)
 ;%0A  
@@ -4268,27 +4268,14 @@
 art(
-getPort(args));    
+port);
 %0A   
@@ -4315,107 +4315,202 @@
 tic 
-int getPort(final String%5B%5D args) %7B%0A        if (0 == args.length) %7B%0A            return DEFAULT_PORT;
+YamlProxyConfiguration getYamlProxyConfiguration(final YamlProxyConfiguration localConfig, final OrchestrationFacade orchestrationFacade) %7B%0A        return localConfig.isEmptyLocalConfiguration()
 %0A   
@@ -4510,34 +4510,32 @@
 n()%0A        
-%7D%0A
         
 try %7B%0A      
@@ -4526,153 +4526,182 @@
     
-try %7B%0A
+ 
        
-     return Integer.parseInt(args%5B0%5D);%0A        %7D catch (final NumberFormatException ex) %7B%0A            return DEFAULT_PORT;%0A        %7D
+? new YamlProxyConfiguration(orchestrationFacade.getConfigService().loadDataSources(), orchestrationFacade.getConfigService().loadProxyConfiguration()) : localConfig;
 %0A   

refactor get port for bootstrap