using System.Text.RegularExpressions;
using Coravel;
using Coravel.Scheduling.Schedule;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SettleAccount.Job.SignalR;
using Win.Sfs.SettleAccount.Entities.BQ;
using Win.Sfs.SettleAccount.Entities.BQ.Syncs;

namespace Win.Sfs.SettleAccount;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScheduler();
        services.AddSignalR(o => o.EnableDetailedErrors = true);
        JobHostdService.AddService(services);
        services.AddSingleton<JobHostdService>();
        services.AddHostedService(o => o.GetRequiredService<JobHostdService>());
        services.AddTransient<HBPOSeSyncAppService>();
        services.AddTransient<BBACSeSyncAppService>();
        services.AddTransient<ZhiGongBBACSeSyncAppService>();
        services.AddRouting(options => options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer));
        services.AddMvc(options => options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer())));
        services.AddApplication<SettleAccountHttpApiHostModule>();
        services.Configure<KestrelServerOptions>(options =>
        {
            // Set the limit to 256 MB
            options.Limits.MaxRequestBodySize = 268435456;
        });
        //上传文件大小限制IIS设置
        services.Configure<IISServerOptions>(options =>
        {
            options.MaxRequestBodySize = 268435456;
            options.AllowSynchronousIO = true;
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseRouting();
        app.UseEndpoints(endpoints => endpoints.MapHub<PageHub>("/api/hub"));
        app.ApplicationServices.UseScheduler(scheduler =>{ });
        var contentTypeProvider = new FileExtensionContentTypeProvider();
        contentTypeProvider.Mappings.Add(".mjs", "text/javascript");
        app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = contentTypeProvider });
        app.InitializeApplication();
    }

    public class SlugifyParameterTransformer : IOutboundParameterTransformer
    {
        public string TransformOutbound(object value)
        {
            if (value == null) { return null; }
            var str = value.ToString();
            if (string.IsNullOrEmpty(str)) { return null; }
            return Regex.Replace(str?.ToString(), "([a-z])([A-Z])", "$1-$2").ToLowerInvariant();
        }
    }
}