using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;

namespace AuthStudy.Authentication.Browser
{
    public static class BrowserAuthenticationExtensions
    {
        #region 基于接口的扩展注册
        public static IServiceCollection AddBrowserAuthentication
        (
           this IServiceCollection builder,
           string AuthenticationSchemeName,
           string AuthenticationDispalyName,
           BrowserAuthenticationOptions Option
        )
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            builder.AddService(Option);

            builder.AddAuthentication(options =>
            {
                options.DefaultScheme = AuthenticationSchemeName;
                options.DefaultAuthenticateScheme = AuthenticationSchemeName;
                options.DefaultChallengeScheme = AuthenticationSchemeName;
                options.DefaultForbidScheme = AuthenticationSchemeName;
                options.DefaultSignInScheme = AuthenticationSchemeName;
                options.DefaultSignOutScheme = AuthenticationSchemeName;

                options.AddScheme<BrowserAuthenticationBaseHandler>(AuthenticationSchemeName, AuthenticationDispalyName);
            });

            return builder;
        }


        private static IServiceCollection AddService(this IServiceCollection builder, BrowserAuthenticationOptions option)
        {
            BrowserAuthenticationOptions defaultOption = option ?? new(){AllowBrowsers = BrowserAuthenticationDefault.AllowBrowsers};
            builder.AddSingleton(defaultOption);
            builder.AddSingleton<BrowserAuthenticationBaseHandler>();

            return builder;
        }

        #endregion
    }
}