package com.zfire.jiasm.syncdata.utils;

import com.zfire.jiasm.syncdata.data.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TokenCenter {
	@Autowired
	private TokenManager tokenManager;
	private Token currentToken;
	private Token currentToken4Pgid;

	public synchronized Token getCurrentToken4Pgid() throws Exception {
		this.currentToken4Pgid = this.getCurrentToken(this.currentToken4Pgid, tokenManager.getClientId4Pgid(),
				tokenManager.getClientSecret4Pgid());
		return this.currentToken4Pgid;
	}

	public synchronized Token getCurrentToken() throws Exception {
		this.currentToken = this.getCurrentToken(this.currentToken, tokenManager.getClientId(),
				tokenManager.getClientSecret());
		return this.currentToken;
	}

	private Token getCurrentToken(Token currentToken, String clientId, String clientSecret) throws Exception {

		if (currentToken == null) {
			return tokenManager.getToken(clientId, clientSecret);
		}

		long tokenUseTime = (System.currentTimeMillis() - currentToken.getCreateTime()) / 1000;
		if (tokenUseTime > currentToken.getExpiresIn()) {
			if (tokenUseTime < currentToken.getRefreshExpiresIn()) {
				return tokenManager.refreshToken(currentToken, clientId, clientSecret);
			} else {
				return tokenManager.getToken(clientId, clientSecret);
			}
		} else {
			return currentToken;
		}

	}

}
