using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.FileProviders;
using WebApiClient;
using System.Globalization;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Localization;
using AMESCoreStudio.Web.Code;
using Microsoft.AspNetCore.Http.Features;

namespace AMESCoreStudio.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // �X�RJSON 
            services.AddControllers().AddNewtonsoftJson();

            // FormPost�ƶq�W��
            services.Configure<FormOptions>(options =>
            {
                options.ValueLengthLimit = 209715200;
                options.ValueCountLimit = int.MaxValue;
            });

            // ModelBinding���ƤW��
            services.AddMvc(options =>
            {
                options.MaxModelBindingCollectionSize = int.MaxValue;
            });

            // ValidationVisitor exceeded the maximum configured validation depth '32'
            services.AddMvc().AddMvcOptions(options =>
            {
                    options.MaxModelValidationErrors = 999999;
            });

            // �ɮץؿ�
            //Add our IFileServerProvider implementation as a singleton
            //services.AddSingleton<IFileServerProvider>(new FileServerProvider(
            //    new List<FileServerOptions>
            //    {
            //        new FileServerOptions
            //        {
            //            // ������|
            //            FileProvider = new PhysicalFileProvider(@"\\10.0.8.7\\shop"),
            //            // �������|
            //            RequestPath = new PathString("/aa"),
            //            EnableDirectoryBrowsing = true
            //        }
            //        new FileServerOptions
            //        {
            //            FileProvider = new PhysicalFileProvider(@"//qasrv-n/Web/ISOZone/"),
            //            RequestPath = new PathString("/DocEsop"),
            //            EnableDirectoryBrowsing = true
            //        }
            //    }));

            var config = Configuration.Get<VirtualPathConfig>().VirtualPath;
            var fileServerOptions = new List<FileServerOptions>();
            if (config != null)
            {
                config.ForEach(f =>
                {
                    fileServerOptions.Add(new FileServerOptions
                    {
                        FileProvider = new PhysicalFileProvider(@f.RealPath),
                        RequestPath = new PathString(f.RequestPath),
                    });
                });
            };
            services.AddSingleton<IFileServerProvider>(new FileServerProvider(fileServerOptions));

            // ���ÿ�����������������Դ
            services.AddCors(options =>
                        options.AddPolicy("AMESPolicy",
                        p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));


            services.AddLocalization(o =>
            {
                o.ResourcesPath = "Resources";
            });

            // Add framework services.
            //services.AddMvc();
            //services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
            services.AddMvc()
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization(options =>
                {
                    options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource));
                });
            //services.AddControllersWithViews();

            services.AddControllersWithViews().AddRazorRuntimeCompilation();

            //ʹ��Session
            services.AddSession();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
              .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
              {
                  options.LoginPath = new PathString("/Login/Index");
                  options.LogoutPath = new PathString("/Login/Logout");
                  options.AccessDeniedPath = new PathString("/Home/Error");
                  options.Cookie.Name = "_AMESCookie";
                  //options.Cookie.SameSite = SameSiteMode.None;

                  //��Cookie ����ʱ���Ѵ�һ��ʱ���Ƿ�����ΪExpireTimeSpan
                  options.SlidingExpiration = true;
                  options.Cookie.HttpOnly = true;
              });

            //����HttpClient���
            var types = typeof(Startup).Assembly.GetTypes()
                        .Where(type => type.IsInterface
                        && ((System.Reflection.TypeInfo)type).ImplementedInterfaces != null
                        && type.GetInterfaces().Any(a => a.FullName == typeof(IHttpApi).FullName));
            foreach (var type in types)
            {
                // �]�w�I�sAPI ����10����
                services.AddHttpApi(type).ConfigureHttpClient(o => { o.Timeout = TimeSpan.FromMinutes(10); });
                services.ConfigureHttpApi(type, o =>
                {
                    o.HttpHost = new Uri(AppSetting.Setting.ApiUrl);
                });
            }

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IFileServerProvider fileServerprovider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseCors("AMESPolicy");

            //app.UseHttpsRedirection();
            app.UseStaticFiles();

            IList<CultureInfo> supportedCultures = new List<CultureInfo>
            {
                new CultureInfo("en-US"),
                new CultureInfo("zh-CN"),
                new CultureInfo("zh-TW")
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-US"),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            });

            app.UseRouting();
            app.UseAuthorization();
            app.UseAuthentication();
            app.UseSession();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Login}/{action=Index}/{id?}");
            });

            app.UseCookiePolicy();

            // �ɮץؿ�
            app.UseFileServerProvider(fileServerprovider);

        }
    }
}