using CloudBuilder.Core.Application.Options;
using CloudBuilder.Core.Policy;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CloudBuilder.Core.Authorization
{
    public class JwtGenerate
    {
        private readonly JwtOptions jwtOptions;

        public JwtGenerate(JwtOptions jwtOptions)
        {
            this.jwtOptions = jwtOptions;
        }

        public string GenerateRefreshToken()
        {
            var randomNumber = new byte[32];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(randomNumber);
                return Convert.ToBase64String(randomNumber);
            }
        }

        public string Generate(Dictionary<string, string> claims)
        {
            JwtOptions jwt = jwtOptions;

            var token = string.Empty;

            List<Claim> claimls = new List<Claim>();
            foreach (var claim in claims)
            {
                claimls.Add(new Claim(claim.Key, claim.Value));
            }

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                NotBefore = DateTime.UtcNow,
                Issuer = jwt.Issuer,
                Audience = jwt.Audience,
                Subject = new ClaimsIdentity(claimls, ClaimPolicy.BEARER, ClaimPolicy.CLAINM_USERID, ClaimPolicy.ROLE),
                Expires = DateTime.UtcNow.AddMinutes(jwt.AccessExpireMins),
                SigningCredentials = credentials
            };

            var securityToken = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(securityToken);
        }
    }
}
