package com.zfire.jiasm.syncdata.utils;

import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.data.Token;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class TokenManager {

	@Value("${clientId}")
	private String clientId;

	public String getClientId() {
		return clientId;
	}

	public String getClientSecret() {
		return clientSecret;
	}

	public String getClientId4Pgid() {
		return clientId4Pgid;
	}

	public String getClientSecret4Pgid() {
		return clientSecret4Pgid;
	}

	@Value("${clientSecret}")
	private String clientSecret;
	
	@Value("${clientId4Pgid}")
	private String clientId4Pgid;

	@Value("${clientSecret4Pgid}")
	private String clientSecret4Pgid;

	@Value("${tokenURL}")
	private String tokenURL;

	public Token getToken(String clientId, String clientSecret) throws Exception {

		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("grant_type", "client_credentials");
		paramMap.put("client_id", clientId);
		paramMap.put("client_secret", clientSecret);
		JSONObject result = HttpUtil.httpRequest(tokenURL, "POST", paramMap,
				"application/x-www-form-urlencoded");

		return new Token(result.getString("access_token"), result.getLong("expires_in"),
				result.getString("refresh_token"), result.getLong("refresh_expires_in"));

	}

	public Token refreshToken(Token oldToken,String clientId,String clientSecret) throws Exception {

		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("grant_type", "refresh_token");
		paramMap.put("client_id", clientId);
		paramMap.put("client_secret", clientSecret);
		paramMap.put("refresh_token", oldToken.getRefreshToken());

		JSONObject result = HttpUtil.httpRequest(tokenURL, "POST", paramMap,
				"application/x-www-form-urlencoded");

		return new Token(result.getString("access_token"), result.getLong("expires_in"),
				result.getString("refresh_token"), result.getLong("refresh_expires_in"));

	}

}
