using Edu.Common.API;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace Edu.WebApi.Helper
{
    /// <summary>
    /// Token帮助类
    /// </summary>
    public class WebApiTokenHelper
    {
        /// <summary>
        /// 生成Token
        /// </summary>
        /// <param name="uid">加密字符串</param>
        /// <param name="requestFromEnum">来源</param>
        /// <returns></returns>
        public static string CreateToken(string uid, Common.Enum.ApiRequestFromEnum requestFromEnum)
        {
            TokenUserInfo userInfo = new TokenUserInfo { Uid = uid, RequestFrom = requestFromEnum };
            IDateTimeProvider provider = new UtcDateTimeProvider();
            var now = provider.GetNow().AddMinutes(-1);
            var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
            var payload = new Dictionary<string, object>()
            {
                {"iat",secondsSinceEpoch },
                {"exp",secondsSinceEpoch+Common.Config.JwtExpirTime},
                {Common.GlobalKey.JWT_User_Key,userInfo }
            };
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            string secret = Common.Config.JwtSecretKey;
            string token = encoder.Encode(payload, secret);
            return token;
        }

        /// <summary>
        /// 解析Token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static JObject AnalysisToken(string token)
        {
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
            string secret = Common.Config.JwtSecretKey;
            //token为之前生成的字符串
            var json = decoder.Decode(token, secret, verify: true);
            JObject jwtJson = JObject.Parse(json);
            return jwtJson;
        }
    }
}