using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace OcelotStudy.Getway
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var builder = Host.CreateDefaultBuilder(args);
            builder
            .ConfigureAppConfiguration((hostingContext, config) =>
             {
                 config
                     .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                     .AddJsonFile("appsettings.json", true, true)
                     .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                     .AddEnvironmentVariables()
                     .AddCommandLine(args);

                 LoadOcelotConfig(config, hostingContext);
             });

            return builder;
        }

        static IConfigurationBuilder LoadOcelotConfig(IConfigurationBuilder config, HostBuilderContext hostingContext)
        {
            var configFromCommandLine = config.Build().GetValue("config", string.Empty);

            //�����в����Ż�
            if (!string.IsNullOrEmpty(configFromCommandLine))
            {
                if (configFromCommandLine.EndsWith(".json"))
                {
                    config.AddJsonFile($"{configFromCommandLine}", true, true);
                }
                else
                {
                    if (configFromCommandLine.StartsWith("ocelot."))
                    {
                        config.AddJsonFile($"{configFromCommandLine}.json", false, true);
                    }
                    else
                    {
                        config.AddJsonFile($"ocelot.{configFromCommandLine}.json", false, true);
                    }
                }
            }
            else
            {
                config
                .AddJsonFile("ocelot.json", false, true)
                .AddJsonFile($"ocelot.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true);
            }

            return config;
        }
    }
}