using Bootstrap.DataAccess.Helper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Linq;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// 自动生成数据库扩展操作类
    /// </summary>
    public static class AutoGenerateDatabaseExtensions
    {
        private static bool _init;
        private static object _locker = new object();
        private const string SqlFolderKey = "SqlFolder";
        /// <summary>
        /// 自动生成数据库中间件
        /// </summary>
        /// <param name="app"></param>
        public static IApplicationBuilder UseAutoGenerateDatabase(this IApplicationBuilder app)
        {
            app.Use(async (context, next) =>
            {
                if (!_init)
                {
                    // 优化性能
                    var config = context.RequestServices.GetRequiredService<IConfiguration>();
                    var autoGenerate = config.GetValue("AutoGenerateDatabase", false);
                    if (!autoGenerate) _init = true;
                    if (autoGenerate)
                    {
                        // 阻止所有线程继续往下运行，等待数据库检查
                        lock (_locker)
                        {
                            if (!_init)
                            {
                                // 数据检查
                                var dbSection = config.GetSection("DB").GetChildren().FirstOrDefault(c => c.GetValue("Enabled", false));
                                if (dbSection != null)
                                {
                                    var folder = dbSection.GetValue(SqlFolderKey, "").ReplaceOSPlatformPath();
                                    if (!string.IsNullOrEmpty(folder))
                                    {
                                        // 判断文件夹是否存在
                                        var env = context.RequestServices.GetRequiredService<IWebHostEnvironment>();
                                        var fullFolder = Path.Combine(env.ContentRootPath, folder);
                                        if (Directory.Exists(fullFolder))
                                        {
                                            try
                                            {
                                                AutoDbHelper.EnsureCreated(fullFolder);
                                            }
                                            catch { }
                                        }
                                    }
                                }
                            }
                            _init = true;
                        }
                    }
                }
                await next();
            });
            return app;
        }
    }
}
