using Back.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Threading.Tasks;


namespace Back.Features
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class CheckOnlineUser
    {
        private readonly RequestDelegate _next;
    
        public CheckOnlineUser(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            int UserID = Convert.ToInt32(httpContext.User.Claims.Where(w => w.Type == "UserID").Select(s => s.Value).FirstOrDefault());
            var accessToken = httpContext.GetTokenAsync("access_token").Result;
            if (UserID==null || UserID==0 || string.IsNullOrEmpty(accessToken))
                await _next(httpContext);
            else
            {
                servUser _servUser = (servUser)httpContext.RequestServices.GetService(typeof(servUser));
                var user =  _servUser.GetUserByUserID(UserID).Result;
                if ((user != null && user.Token==accessToken) || httpContext.GetEndpoint().DisplayName.Contains("BaseController"))
                    await _next(httpContext);
                else
                    httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                
            }
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class CheckOnlineUserExtensions
    {
        public static IApplicationBuilder UseCheckOnlineUser(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CheckOnlineUser>();
        }
    }
}
