package com.leanwo.activiti.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.leanwo.activiti.exception.TokenException;

/**
 * token 密钥配置.
 *
 * @author YangZhiJie
 */
@Configuration
@RefreshScope
public class TokenConfiguration {

	private static Logger logger = LoggerFactory.getLogger(TokenConfiguration.class);

	/** token 密钥. */
	@Value("${server.token.secret}")
	private String tokenSecret;

	/** token 授权单位. */
	@Value("${server.token.issuer}")
	private String tokenIssuer;

	/** token超时时间. */
	@Value("${server.token.invalidSecond}")
	private long tokenInvalidSecond;

	/**
	 * Gets the token 密钥.
	 *
	 * @return the token 密钥
	 */
	public String getTokenSecret() {
		return tokenSecret;
	}

	/**
	 * Sets the token 密钥.
	 *
	 * @param tokenSecret the new token 密钥
	 */
	public void setTokenSecret(String tokenSecret) {
		this.tokenSecret = tokenSecret;
	}

	/**
	 * Gets the token 授权单位.
	 *
	 * @return the token 授权单位
	 */
	public String getTokenIssuer() {
		return tokenIssuer;
	}

	/**
	 * Sets the token 授权单位.
	 *
	 * @param tokenIssuer the new token 授权单位
	 */
	public void setTokenIssuer(String tokenIssuer) {
		this.tokenIssuer = tokenIssuer;
	}

	/**
	 * Gets the token超时时间.
	 *
	 * @return the token超时时间
	 */
	public long getTokenInvalidSecond() {
		return tokenInvalidSecond;
	}

	/**
	 * Sets the token超时时间.
	 *
	 * @param tokenInvalidSecond the new token超时时间
	 */
	public void setTokenInvalidSecond(long tokenInvalidSecond) {
		this.tokenInvalidSecond = tokenInvalidSecond;
	}

	/**
	 * 加密算法
	 * 
	 * @return
	 */
	@Bean
	public Algorithm algorithm() {
		try {
			Algorithm algorithm = Algorithm.HMAC256(tokenSecret);
			return algorithm;
		} catch (IllegalArgumentException e) {
			logger.error("获取Token加密算法失败", e);
			throw new TokenException("获取Token加密算法失败");
		}
	}

	/**
	 * 
	 * JWT 验证器
	 * 
	 * @return
	 */
	@Bean
	public JWTVerifier jWTVerifier() {
		JWTVerifier jWTVerifier = JWT.require(algorithm()).withIssuer(tokenIssuer) // 签发者
				.build();
		return jWTVerifier;
	}
}
