using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using XYY.Service.Standard.RegionService;
using XYY.Authentication.Standard;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using XYY.Api.Finance.Controllers;
using XYY.Service.Standard.Finance;

namespace XYY.Api.Finance
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";//Ãû×ÖËæ±ãÆð


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddXYYService(new ServiceOption
            {
                PBESConnection = Configuration[DefaultConfig.ESUrlKey],
                USEDBTransferAsMVC = true,
                CacheType = DistributedCacheType.Redis,
                SqlServiceConnection = Configuration[DefaultConfig.SqlServiceConnectionKey],
                RedisConnection = Configuration[DefaultConfig.RedisConnectionKey],
                UseRabbit = true,
               
            }, Configuration);
            services.AddCors(option => option.AddPolicy(MyAllowSpecificOrigins, policy =>
            policy.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod()));
            services.AddControllers().AddNewtonsoftJson(options =>
            { 
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();

            });
            services.AddSignalR();

            services.AddAuthentication(BasicAuthenticationScheme.DefaultScheme)
                .AddScheme<BasicAuthenticationOption, BasicAuthenticationHandler>(BasicAuthenticationScheme.DefaultScheme, null
                ); 
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStatusCodePages();
            app.UseRouting();
            app.UseCors(MyAllowSpecificOrigins);
            app.UseWebSockets();
            app.UseBasicAuthentication();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<BatchInputHub>("/BatchInput");
            });

        }
    }
}
