package com.sonic.lion.utils;

import com.google.common.collect.ImmutableMap;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;


@Slf4j
public class JwtUtils {

    public static final String KID = "8ZWMTXTQMS";
    public static final String ISSUER_ID = "567ad6cc-22b8-44aa-8ff0-7f2b88f1c418";
    private static final String PK = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgv+SthbyYfUmy/+r0OlUl0vDynQWf+AH3zazlm/zeM3agCgYIKoZIzj0DAQehRANCAAQ/NG6BS0y6zI+ITjJGoLPW4Ucdto8B/9lAnzkTVNCrJ5MNFbp6nS0+AlfnbwgELGOIR0Zz0YbGAINZ9qxcGyGz";

    public static String getAppleJwt(String bundleId) throws Exception {
        long nowMillis = System.currentTimeMillis();//生成JWT的时间
        long expMillis = nowMillis + 200000;
        Date now = new Date(nowMillis);
        Date exp = new Date(expMillis);

        JwtBuilder builder = Jwts.builder().setHeaderParam("kid", KID)
                .setClaims(ImmutableMap.of("bid", bundleId, "nonce", UUID.randomUUID().toString()))
                .setIssuer(ISSUER_ID)
                .setIssuedAt(now)
                .setAudience("appstoreconnect-v1")
                .setExpiration(exp)
                .signWith(getPk());
        return builder.compact();
    }

    public static String getJwtBody(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) {
            return null;
        }
        System.out.println("------------ Decode JWT ------------");
        String[] split_string = jwtToken.split("\\.");
        String base64EncodedHeader = split_string[0];
        String base64EncodedBody = split_string[1];
        String base64EncodedSignature = split_string[2];

        System.out.println("~~~~~~~~~ JWT Body ~~~~~~~");
        String body = new String(Base64.getDecoder().decode(base64EncodedBody));
        return body;
    }

    /**
     * 根据 私钥字符串获取 PrivateKey 对象
     *
     * @return
     * @throws Exception
     */
    public static PrivateKey getPk() throws Exception {
        byte[] encoded = Base64.getDecoder().decode(PK);
        PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("EC"); //ES256 算法。
        PrivateKey unencryptedPrivateKey = kf.generatePrivate(kspec);
        return unencryptedPrivateKey;
    }
}