package com.xingxi.api.common;

import com.xingxi.common.utils.DateUtils;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.UUID;

public final class JWTUtils {
    private static final String SECRET_KEY_STRING = "9YIGtSIjKI2cGGz7TuPNQFtk2WmphzESAp98zicd6AI=";
    private JWTUtils(){
        throw new RuntimeException();
    }


    public static String generateSecretKeyString(){
        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        return Encoders.BASE64.encode(key.getEncoded());
    }


    public static String generateJwtString(String openid, Date issuedAt){
        SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET_KEY_STRING));
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setId(UUID.randomUUID().toString()) // jti
                .setSubject(openid) // sub 主题
                .setExpiration(DateUtils.addHours(new Date(), 4)) //过期时间
                .setIssuedAt(issuedAt) // 发布时间
                .setIssuer("Biandan_wx_") // 发布者
//                .claim("test", "1231333")
                .signWith(secretKey)
                .compact();
    }


    public static Jws<Claims> parseJwt(String compactJws){
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY_STRING)
                    .build().parseClaimsJws(compactJws);
            Claims body = claimsJws.getBody();
            JwsHeader header = claimsJws.getHeader();
            System.out.println(body);
            System.out.println(header);
            //OK, we can trust this JWT
            return claimsJws;
        } catch (JwtException e) {
            //don't trust the JWT!
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    public static void main(String[] args) {
//        String secretString = generateSecretKeyString();
//        System.out.println(secretString);
//        String test = generateJwtString(new HashMap<String, String>(){{
//            put("test", "1213");
//        }});
//        System.out.println(test);
//        parseJwt(test);
    }


}
