using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace ClaimsSample.Extensions
{
    public class MinimumAgeRequirement: AuthorizationHandler<MinimumAgeRequirement>,IAuthorizationRequirement
    {
        public int MinimumAge { get; private set; }

        public MinimumAgeRequirement(int minimumAge)
        {
            MinimumAge = minimumAge;
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinimumAgeRequirement requirement)
        {
            if (context.User != null)
            {
                if (context.User.HasClaim(c => c.Type == ClaimTypes.Role && c.Value == "演示组"))
                {
                    var dateOfBirth = Convert.ToDateTime(context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth).Value);

                    int caculateAge = DateTime.Today.Year - dateOfBirth.Year;

                    if (caculateAge >= requirement.MinimumAge)
                    {
                        context.Succeed(requirement);
                    }
                }

                if (context.User.Identity.Name == "admin")
                {
                    context.Succeed(requirement);
                }
            }

            if (context.User.Identity.Name == "zhangsan")
            {
                context.Fail();
            }

            return Task.CompletedTask;
        }
    }
}
