package ink.wgink.module.oauth2.manager;

import com.alibaba.fastjson.JSONObject;
import ink.wgink.module.oauth2.pojo.AccessToken;
import ink.wgink.module.oauth2.remote.IAccessTokenRemoteService;
import ink.wgink.properties.ApiPathProperties;
import ink.wgink.properties.oauth2.client.OAuth2ClientProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: ClientTokenManager
 * @Description: 客户单token
 * @Author: WangGeng
 * @Date: 2019/10/16 12:22 上午
 * @Version: 1.0
 **/
public class OAuth2ClientTokenManager {

    private static final Logger LOG = LoggerFactory.getLogger(OAuth2ClientTokenManager.class);
    private static OAuth2ClientTokenManager oAuth2ClientTokenManager = OAuth2ClientTokenBuilder.oAuth2ClientTokenManager;
    private AccessToken accessToken;
    private IAccessTokenRemoteService accessTokenRemoteService;
    private OAuth2ClientProperties oAuth2ClientProperties;
    private ApiPathProperties apiPathProperties;

    private OAuth2ClientTokenManager() {
    }

    public static OAuth2ClientTokenManager getInstance() {
        return oAuth2ClientTokenManager;
    }

    public AccessToken getToken() {
        if (accessToken == null || (System.currentTimeMillis() - accessToken.getCreateTime()) / 1000 >= accessToken.getExpiresIn()) {
            LOG.debug("客户端Token失效，获取token");
            JSONObject accessTokenJsonObject = accessTokenRemoteService.getAccessToken(apiPathProperties.getUserCenter(), "client_credentials", oAuth2ClientProperties.getClient().getClientId(), oAuth2ClientProperties.getClient().getClientSecret(), "all");
            accessToken = new AccessToken();
            accessToken.setAccessToken(accessTokenJsonObject.getString("access_token"));
            accessToken.setTokenType(accessTokenJsonObject.getString("token_type"));
            accessToken.setExpiresIn(accessTokenJsonObject.getInteger("expires_in"));
            accessToken.setScope(accessTokenJsonObject.getString("scope"));
            accessToken.setJti(accessTokenJsonObject.getString("jti"));
            accessToken.setCreateTime(System.currentTimeMillis());
        }
        return accessToken;
    }

    public void setAccessTokenRemoteService(IAccessTokenRemoteService accessTokenRemoteService) {
        this.accessTokenRemoteService = accessTokenRemoteService;
    }

    public void setOAuth2ClientProperties(OAuth2ClientProperties oAuth2ClientProperties) {
        this.oAuth2ClientProperties = oAuth2ClientProperties;
    }

    public void setApiPathProperties(ApiPathProperties apiPathProperties) {
        this.apiPathProperties = apiPathProperties;
    }

    private static class OAuth2ClientTokenBuilder {
        public static OAuth2ClientTokenManager oAuth2ClientTokenManager = new OAuth2ClientTokenManager();
    }

}
