using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using TEAMModelOS.SDK.Extension;
using System;
using TEAMModelOS.Models;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;

namespace TEAMModelOS.Filter
{
    public class ApiTokenAttribute : Attribute, IFilterFactory
    {
        public bool IsReusable => true;
        //public string Roles { get; set; }
        //public string Permissions { get; set; }

        public IFilterMetadata CreateInstance(IServiceProvider services)
        {
            var option = services.GetService<IOptions<Option>>();
            return new InternalAuthTokenFilter(option);
        }

        private class InternalAuthTokenFilter : IResourceFilter
        {
            private readonly Option _option;
            //private readonly string _roles;
            //private readonly string _permissions;

            public InternalAuthTokenFilter(IOptions<Option> option)
            {
                _option = option.Value;
                //_roles = roles;
                //_permissions = permissions;
            }
            public void OnResourceExecuting(ResourceExecutingContext context)
            {
                bool pass = false;
                string id = string.Empty, name = string.Empty, school = string.Empty,jti=string.Empty;

                var authtoken = context.HttpContext.GetXAuth("ApiToken");
                if (!string.IsNullOrWhiteSpace(authtoken) && JwtAuthExtension.ValidateApiToken(authtoken, _option.JwtSecretKey))
                {
                    var jwt = new JwtSecurityTokenHandler().ReadJwtToken(authtoken);
                    id = jwt.Payload.Sub;
                    school = jwt.Payload.Azp;
                    jti = jwt.Payload.Jti;
                    name = jwt.Claims.FirstOrDefault(claim => claim.Type == "name")?.Value;
                    //处理限流问题
                    if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(school) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(jti))
                    {
                        context.Result = new BadRequestResult();
                    }
                    else { 
                        
                    }
                }

                if (pass)
                {
                    context.HttpContext.Items.Add("ID", id);
                    context.HttpContext.Items.Add("Name", name);
                    context.HttpContext.Items.Add("School", school);
                }
                else
                    context.Result = new BadRequestResult();
            }

            public void OnResourceExecuted(ResourceExecutedContext context)
            {
            }
        }
    }
}
