package cn.myapps.runtime.rest.security.service;

import java.security.Key;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.springframework.stereotype.Service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * AccessToken服务的JWT实现
 * @author zhanbo
 */
@Service
public class JwtAccessTokenServiceImpl implements AccessTokenService{

    /**
     * AccessToken过期时间
     */
    private final int TTLMillis = 1000*3600;

    @Override
    public Boolean checkAccessToken(String accessToken,String secretKey) throws ExpiredJwtException,Exception {
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(secretKey))
                .parseClaimsJws(accessToken).getBody();

        //获取主题
        String secret = claims.getSubject();

        System.out.println("secret->"+secret);
        
//        SuperUserDesignTimeService superUserService = DesignTimeServiceManager.superUserDesignTimeService();
//        SuperUserVO superUserVO = superUserService.getSuperUserBySecret(secret);
//        if(superUserVO == null) {
//            return false;
//        }

        return true;
    }

    @Override
    public String generateAccessToken(String secret,String secretKey) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        //生成签名密钥 就是一个base64加密后的字符串
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary (secretKey);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes,signatureAlgorithm.getJcaName());
        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .setIssuedAt(now)
                .setSubject(secret)
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (TTLMillis >= 0) {
            //过期时间
            long expMillis = nowMillis + TTLMillis;
            //现在是什么时间
            Date exp = new Date(expMillis);
            //系统时间之前的token都是不可以被承认的
            builder.setExpiration(exp).setNotBefore(now);
        }
        //生成JWT
        return builder.compact();
    }


    public static void main(String[] args) {
        String token = new JwtAccessTokenServiceImpl().generateAccessToken("12345","teemlink_obpm");
        System.out.println(token);
    }
}
