using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Helper;
namespace WIDESEA_Core.Extensions
{
    /// 
    /// Cors 跨域
    /// 
    public static class CorsSetup
    {
        /// 
        /// 跨域
        /// 
        /// 
        /// 
        public static void AddCorsSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            services.AddCors(c =>
            {
                if (!AppSettings.Get(new string[] { "Cors", "EnableAllIPs" }).ObjToBool())
                {
                    c.AddPolicy(AppSettings.Get(new string[] {"Cors", "PolicyName" }),
                        policy =>
                        {
                            policy
                            .WithOrigins(AppSettings.Get(new string[] { "Cors", "IPs" }).Split(','))
                            .AllowAnyHeader()//Ensures that the policy allows any header.
                            .AllowAnyMethod();
                        });
                }
                else
                {
                    //允许任意跨域请求
                    c.AddPolicy(AppSettings.Get(new string[] { "Cors", "PolicyName" }),
                        policy =>
                        {
                            policy
                            .SetIsOriginAllowed((host) => true)
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials();
                        });
                }
            });
        }
    }
}