using System;
using System.Collections.Generic;
using System.Text;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;

namespace DFS.Core.Mvc.Jwt.Impl
{
    /// <summary>
    /// 以JWT算法实现的web token 管理类
    /// </summary>
    public class JWTManager : ITokenManager
    {
        private IJwtEncoder encoder;
        private IJwtDecoder decoder;
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="payload">非敏感信息</param>
        /// <param name="secret">密钥</param>
        /// <returns></returns>
        public string BuildToken(object payload, string secret)
        {
            return encoder.Encode(payload, secret);
        }
        /// <summary>
        /// 解码token获取json信息
        /// </summary>
        /// <param name="token">token</param>
        /// <param name="secret">密钥</param>
        /// <param name="verify">是否验证签名后再返回解码信息</param>
        /// <returns></returns>
        public string DecodeToken(string token, string secret, bool verify = true)
        {
            return decoder.Decode(token, secret, verify);
        }
        /// <summary>
        /// 解码token获取json信息
        /// </summary>
        /// <param name="token">token</param>
        /// <param name="secret">密钥</param>
        /// <param name="verify">是否验证签名后再返回解码信息</param>
        /// <returns></returns>
        public T DecodeToken<T>(string token, string secret, bool verify = true)
        {
            return decoder.DecodeToObject<T>(token, secret, verify);
        }

        /// <summary>
        /// 构造函数初始化
        /// </summary>
        public JWTManager()
        {
            if (encoder == null)
            {
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJsonSerializer serializer = new JsonNetSerializer();
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            }
            if (decoder == null)
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                decoder = new JwtDecoder(serializer, urlEncoder);
            }
        }
    }
}
