using HTEXLib.Builders;
using HTEXLib.Translator;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.SpaServices;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TEAMModelOS.Models;
using TEAMModelOS.SDK.Context.Configuration;
using TEAMModelOS.SDK.DI;
using VueCliMiddleware;

namespace HiTeachCC
{
    public class Startup
    {
        private IWebHostEnvironment _env { get; set; }
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            _env = env;
            Configuration = configuration;
            BaseConfigModel.SetBaseConfig(Configuration, env.ContentRootPath, env.WebRootPath);
        }

        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)
        {
            services.AddControllersWithViews();
            //設定跨域請求
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins("http://teammodelos-test.chinacloudsites.cn",
                                        "https://www.teammodel.cn", "https://localhost:5001",
                                        "http://localhost:5000", "http://localhost:64524",
                                        "https://localhost:44341", "https://localhost:8888", "http://localhost:8888")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            services.AddAzureStorage(Configuration.GetValue<string>("Azure:Starage:ConnectionString"));
          //  services.AddSnowflakeId(Convert.ToInt64(Configuration.GetValue<string>("Option:LocationNum")), 1);
           // services.AddHttpClient();
            //services.AddHttpClient<DingDing>();
           // services.AddMemoryCache();
            services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = false; });
            //HttpContextAccessor，并用来访问HttpContext。(提供組件或非控制器服務存取HttpContext)
            // services.AddHttpContextAccessor();
            // services.Configure<Option>(options => Configuration.GetSection("Option").Bind(options));
            string path = $"{ _env.ContentRootPath}/JwtRsaFile";
            services.AddHtexTranslator(path);
            services.AddHttpClient();
        }

        // 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.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseCors(MyAllowSpecificOrigins); //使用跨域設定
            //app.UseHttpsRedirection(); //開發中暫時關掉

            //如果应用使用身份验证/授权功能（如 AuthorizePage 或 [Authorize]），请将对 UseAuthentication 和 UseAuthorization的
            //调用放在之后、UseRouting 和 UseCors，但在 UseEndpoints之前
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
#if DEBUG
                endpoints.MapToVueCliProxy(
                    "{*path}",
                    new SpaOptions { SourcePath = "ClientApp" },
                    npmScript: (System.Diagnostics.Debugger.IsAttached) ? "serve" : null,
                    // regex: "Compiled successfully",
                    forceKill: true
                    );
#else
                endpoints.MapFallbackToFile("index.html");
#endif             

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