using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Helpers;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using backstage.Helpers;

using backstage.Models;
using System.Globalization;
using Microsoft.AspNetCore.Localization;

namespace backstage
{
    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)
        {

            double LoginExpireMinute = Convert.ToDouble(Configuration["LoginExpireMinute"]);
            services.AddControllersWithViews();
            services.AddAuthorization();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie("Cookies", option =>
            {

                option.Cookie.HttpOnly = true;
                option.LoginPath = new PathString("/User/Login");
                option.LogoutPath = new PathString("/User/Logout");
                option.Cookie.Name = "backstage";
                option.Cookie.SameSite = SameSiteMode.Strict;
                option.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToAccessDenied = context =>
                    {
                        context.Response.Redirect("/Home/AccessDenied"); // 將使用者重新導向到 Home/AccessDenied
                        return Task.CompletedTask;
                    }
                };

            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("AdminOnly", policy =>
                {
                    // 設定需要 "Admin" 角色的策略
                    policy.RequireRole("Admin");
                });
            });

            services.AddDistributedMemoryCache();

            services.AddHttpContextAccessor();


            services.AddSession(options =>
            {
                options.Cookie.Name = "TokenVault";
                options.IdleTimeout = TimeSpan.FromMinutes(LoginExpireMinute);
                options.Cookie.HttpOnly = true;
            });
            services.AddAntiforgery(
                opts =>
                {
                    opts.Cookie.Name = "anticsrf";
                    opts.FormFieldName = "anticsrf";
                });

            services.AddScoped<ICallApi, CallApi>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddControllersWithViews()
                            .AddViewLocalization(); // 添加視圖本地化支持
          
           

        }

        // 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();
            }
            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.UseStatusCodePagesWithRedirects("/Home/Error"); 
            }
            app.UseAuthentication();

            //�Ϥ��]CSP���Y�L�k���J �ݳB�z
            //app.Use(async (context, next) =>
            //{
            //    context.Response.Headers.Add(
            //        "Content-Security-Policy",
            //        //"style-src 'self' 'sha256-aqNNdDLnnrDOnTNdkJpYlAxKVJtLt9CtFLklmInuUAE=';" +
            //        "img-src 'self';" +
            //        "frame-src https://calendar.google.com/;"+
            //        "script-src 'self' 'nonce-KUY8VewuvyUYVEIvEFue4vwyiuf';" +
            //        "frame-ancestors 'none';"

            //    );
            //    context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
            //    context.Response.Headers.Add("X-Frame-Options", "DENY");
            //    context.Response.Headers.Add("X-Xss-Protection", "1");
            //    await next();
            //});


            // SessionMiddleware �[�J Pipeline
            app.UseSession();
            app.UseHttpsRedirection();

            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization(); // 將 app.UseAuthorization() 放在 app.UseRouting() 之後
           
            app.UseCookiePolicy();


            var supportedCultures = new CultureInfo[] {
                //new CultureInfo("en-US"),
                new CultureInfo("zh"),
                new CultureInfo("en"),
            };
            app.UseRequestLocalization(new RequestLocalizationOptions()
            {
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures,
                //當預設Provider偵測不到用戶支持上述Culture的話，就會是↓
                DefaultRequestCulture = new RequestCulture("zh")//Default UICulture、Culture 
            });

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