using Hncore.Infrastructure.Service;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.Vpn.Domain;
using Hncore.Pass.Vpn.Job;
using Hncore.Pass.Vpn.Map;
using Hncore.Pass.Vpn.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;

namespace Hncore.Pass.Vpn
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        private IServiceProvider _IServiceProvider;

        public Startup(IHostingEnvironment env)
        {
            Configuration = env.UseAppsettings();
        }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<CourseContext>(opt => { opt.UseMySql(Configuration["MySql"]); });
            services.AddTransient<AgentClientLogHandler>();
            services.AddHttpClient("agentClient", c =>
            {
                c.DefaultRequestHeaders.Add("hl", "hl");
            })
            .AddHttpMessageHandler<AgentClientLogHandler>()
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() { UseCookies = false});

            services.AddHttpClient("agentClient1.0", c =>
            {
                c.DefaultRequestHeaders.Add("hl", "hl");
            })
            .AddHttpMessageHandler<AgentClientLogHandler>()
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() { UseCookies = false,AllowAutoRedirect=false });

            services.AddServiceClient(Configuration["Service_BaseUrl"]);
            services.AutoAddService();        
            return _IServiceProvider=services.Init(Configuration, CompatibilityVersion.Version_2_2, new ServiceOption
            {
                 UseGlobalManageAuthFilter = false
            });
        }

        public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime
            , ILoggerFactory loggerFactory)
        {
            MapConfig.Config();

            app.Init(loggerFactory, applicationLifetime);
            //启动后台任务
            applicationLifetime.ApplicationStarted.Register(() =>
            {
               // OrderAccountJob.Start(_IServiceProvider);
                //RefrushStatusJob.Start(_IServiceProvider);
                // ChargeTryJob.Start(_IServiceProvider);
                ExpireTipJob.Start(_IServiceProvider);
            });
        }
    }
}
