using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;

namespace Knoks.Api.Authentication
{
    public static class JwtExtentions
    {
        public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, IConfigurationRoot Configuration, SymmetricSecurityKey signingKey)
        {
            var jwtIssuerOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = jwtIssuerOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience = jwtIssuerOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                RequireExpirationTime = true,
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero
            };

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(cfg => 
            {
                cfg.TokenValidationParameters = tokenValidationParameters;
                cfg.Events = new JwtBearerEvents
                {
                    //OnAuthenticationFailed = context =>
                    //{
                    //    return Task.FromResult(0);
                    //},
                    //OnTokenValidated = context =>
                    //{
                    //    return Task.FromResult(0);
                    //}
                };

            });

            return services;
        }

        private static DateTimeOffset DateTimeOffset = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
        /// <returns>Date converted to seconds since Unix epoch (Jan 1, 1970, midnight UTC).</returns>
        public static long ToUnixEpochDate(this DateTime date) => (long)(date.ToUniversalTime() - DateTimeOffset).TotalSeconds;
    }
}
