package org.shunt.common;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.admin.major.domain.StudentInfo;
import org.shunt.contorller.response.AuthorDTO;

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

public class JWTAuthUtil {
    private static final SignatureAlgorithm signatureAlgorithm;
    private static Key secretKey;
    private static ThreadLocal<AuthorDTO> localAuth;

    public JWTAuthUtil() {
    }

    public static String createJWT(StudentInfo studentInfo){
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.setSubject(studentInfo.getStudentId());

        jwtBuilder.claim("yearId", studentInfo.getYear());
        jwtBuilder.claim("collegeId", studentInfo.getCollegeId());
        jwtBuilder.claim("studentNo", studentInfo.getStudentNo());

        jwtBuilder.claim("issuer", "shunt auth JWT Issuer 1.0");

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, 2);
        jwtBuilder.setExpiration(calendar.getTime());
        jwtBuilder.signWith(signatureAlgorithm, secretKey);
        return jwtBuilder.compact();
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        KeyGenerator instance = KeyGenerator.getInstance(SignatureAlgorithm.HS512.getJcaName());
        SecretKey secretKey = instance.generateKey();
        byte[] encoded = secretKey.getEncoded();
        byte[] decode = Base64.getEncoder().encode(encoded);
        System.out.println(new String(decode));
    }

    public static String createJWT(Map<String, String> auth, String userId, Date expiration) {
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.setSubject(userId);

        for (String key : auth.keySet()) {
            jwtBuilder.claim(key, auth.get(key));
        }
        jwtBuilder.claim("issuer", "shunt auth JWT Issuer 1.0");
        jwtBuilder.setExpiration(expiration);
        jwtBuilder.signWith(signatureAlgorithm, secretKey);
        return jwtBuilder.compact();
    }

    public static void parseJWT(String token, AuthorDTO auth) {
        try {
            Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
            auth.setUserId(claims.getSubject());
            Object yearId = claims.get("yearId");
            Object collegeId = claims.get("collegeId");
            Object studentNo = claims.get("studentNo");
            auth.setYearId(yearId == null ? null : Integer.parseInt(yearId.toString()));
            auth.setCollegeId(collegeId == null ? null : collegeId.toString());
            auth.setStudentNo(studentNo == null ? null : studentNo.toString());
            localAuth.set(auth);
        } catch (ExpiredJwtException var7) {
            throw new XmoseException(XmoseResponse.CODE_TOKEN_EXPIRED,"授权失败未授权");
        } catch (MalformedJwtException var8) {
            throw new XmoseException(XmoseResponse.CODE_TOKEN_EXPIRED,"授权失败未授权");
        } catch (JwtException var9) {
            throw new XmoseException(XmoseResponse.CODE_TOKEN_EXPIRED,"授权失败未授权");
        }
    }

    public static AuthorDTO getAuth() {
        return localAuth.get();
    }

    public static void setAuth(AuthorDTO auth) {
        localAuth.set(auth);
    }

    static {
        signatureAlgorithm = SignatureAlgorithm.HS512;
        secretKey = new SecretKeySpec(Base64.getDecoder().decode("Ihs0fXo2yDuYdFmdtOAslrikP+3rAsumhSYLDacMtjo978/nPsAAV1nuQrOSNvCcEAyb0vvr9vjDcX3URonrrA=="), signatureAlgorithm.getJcaName());
        localAuth = new ThreadLocal<AuthorDTO>();
    }
}