using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Infra.EFCore;
using System.Linq;
using System.Threading.Tasks;

namespace IRaCIS.Core.IdentityServer4.Account
{
    public class AdminResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly IRepository<User> _userRepository;

        public AdminResourceOwnerPasswordValidator(IRepository<User> userRepository)
        {
            _userRepository = userRepository;
        }

        /// <summary>
        /// 验证登录信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public  Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var user =  _userRepository.Where(a => a.UserName == context.UserName&&a.Password==context.Password).FirstOrDefault();

            if (user == null)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "账号/密码输入有误!");
                return Task.CompletedTask;
            }

            //var password = MD5Encrypt.Encrypt32(context.Password);
            //if (user.Password != password)
            //{
            //    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "密码输入有误!");
            //    return;
            //}

            context.Result = new GrantValidationResult(user.Id.ToString(), OidcConstants.AuthenticationMethods.Password);

            return Task.CompletedTask;
        }
    }
}