using CloudBuilder.Core.Application.Builders;
using CloudBuilder.Core.DatabaseAccessor;
using CloudBuilder.Core.DependencyInjection.Form;
using CloudBuilder.Core.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.FileSystemGlobbing;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;

namespace Microsoft.Extensions.DependencyInjection
{
    public static partial class ServiceExtensions
    {
        /// <summary>
        /// 添加依赖注入接口
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection Initialize(this IServiceCollection services)
        {
            IConfiguration configuration = GetConfiguration();
            services.AddSingleton(configuration);

            CloudBuilderBuilder builder = new CloudBuilderBuilder(services, configuration);
            builder.AddPack();

            services.AddSingleton(builder);

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver = new DefaultContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DateFormatString = "yyyy-MM-dd HH:mm:ss"
            };

            return services;
        }
        public static IServiceProvider Build(this IServiceCollection services)
        {
            var serviceProvider = services.BuildServiceProvider();

            //初始化WinForm系统环境变量
            ApplicationServiceContext applicationServiceContext = serviceProvider.GetService<ApplicationServiceContext>()!;

            return serviceProvider;
        }

        public static IConfiguration GetConfiguration()
        {
            var entryAssembly = Assembly.GetEntryAssembly();
            string localentryAssembly = Path.GetFileNameWithoutExtension(entryAssembly.ManifestModule.Name);
            var configuration = new ConfigurationBuilder();

            // 获取程序执行目录
            var executeDirectory = AppContext.BaseDirectory;

            // 获取自定义配置扫描目录
            var configurationScanDirectories = (configuration.Build().GetSection("ConfigurationScanDirectories")
                    .Get<string[]>()
                ?? Array.Empty<string>()).Select(u => Path.Combine(executeDirectory, u));

            // 扫描执行目录及自定义配置目录下的 *.json 文件
            var jsonFiles = new[] { executeDirectory }
                                .Concat(configurationScanDirectories)
                                .SelectMany(u =>
                                    Directory.GetFiles(u, "*.json", SearchOption.TopDirectoryOnly));

            // 如果没有配置文件，中止执行
            if (!jsonFiles.Any()) return configuration.Build();

            // 循环加载
            foreach (var jsonFile in jsonFiles)
            {
                //存在应用名的不加入
                if (Path.GetFileName(jsonFile).Contains(localentryAssembly)) continue;

                configuration.AddJsonFile(jsonFile, optional: true, reloadOnChange: true);
            }

            return configuration.Build();
        }
    }
}