using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SlnMesnac.Config;
using SlnMesnac.Extensions;
using SlnMesnac.Ioc;
using SlnMesnac.Redis;
using SlnMesnac.Serilog;

namespace SlnMesnac.WCS
{
    public class Startup
    {
        private System.Threading.Mutex? mutex = null;

        /// <summary>
        ///
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            bool ret;
            mutex = new System.Threading.Mutex(true, System.Diagnostics.Process.GetCurrentProcess().ProcessName, out ret);
            if (!ret)
            {
                Console.WriteLine("应用程序已开启，禁止重复运行");
                Environment.Exit(0);
            }
            Configuration = configuration;
        }

        /// <summary>
        ///
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        [Obsolete]
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            // 注册 SerilogHelper 服务
            services.AddSingleton<SerilogHelper>();

            services.AddSingleton<RedisHandler>();

            //注册AppConfig
            services.AddSingleton<AppConfig>(provider =>
            {
                var configuration = provider.GetService<IConfiguration>();
                return configuration.GetSection("AppConfig").Get<AppConfig>();
            });

            //注册ORM
            services.AddSqlSugarSetup();

            //注册PLC工厂
            services.AddPlcFactorySetup();

            services.AddRfidFactorySetup();
        }

        /// <summary>
        /// AutoFac自动注入
        /// </summary>
        /// <param name="builder"></param>
        public void ConfigureContainer(ContainerBuilder builder)
        {
            DependencyConfigurator.Configure(builder);
        }

        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //启用Serilog中间件
            app.UseSerilogExtensions();
        }
    }
}