using BPA.MQTTClient;
using BPA.SAAS.Manage.Application.System.Dtos;
using BPA.SAAS.Manage.Core;
using FluentValidation.AspNetCore;
using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConsoleFormatter();
            services.AddJwt<JwtHandler>();
            CosConfig.cosInfoOptions = new CosInfoOptions(App.Configuration["cos_config:AppId"],
    App.Configuration["cos_config:Region"], App.Configuration["cos_config:Bucket"],
    App.Configuration["cos_config:SecretId"], App.Configuration["cos_config:SecretKey"]);
            services.AddControllersWithViews()
           .AddFluentValidation(fv =>
           {
               fv.RegisterValidatorsFromAssemblies(App.Assemblies);
           })
      .AddNewtonsoftJson(options =>
      {
          options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
          options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
      });
            services.AddMqttClientHostedService(op =>
            {
                op.Port = int.Parse(App.Configuration["dev1_brokerHostSettings:Port"]);
                op.Server = App.Configuration["dev1_brokerHostSettings:Host"];
                op.UserName = App.Configuration["MqttClientSettings:UserName"];
                op.Password = App.Configuration["MqttClientSettings:Password"];
                op.mqttClientConnectedHandlerDelegate = new MqttClientConnectedHandlerDelegate(async e =>
                {
                    Console.WriteLine("MQTT连接成功");
                });
                op.mqttClientDisconnectedHandlerDelegate = new MqttClientDisconnectedHandlerDelegate(async e =>
                {
                    Console.WriteLine("MQTT断开连接");
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    try
                    {
                        //var options = op.Server.GetService<IMqttClientOptions>();
                        //await op.Server.GetService<IMqttClient>().ConnectAsync(options);
                    }
                    catch (global::System.Exception)
                    {


                    }
                });
                op.MqttApplicationMessageReceivedHandler = new MQTTnet.Client.Receiving.MqttApplicationMessageReceivedHandlerDelegate(async e =>
                {

                });
            });
            services.AddRemoteRequest();
            services.AddCorsAccessor();
            services.AddSqlsugarSetup(App.Configuration);
            services.AddControllers()
                    .AddInjectWithUnifyResult();
            services.AddMvcFilter<RequestAuditFiltercs>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}