package eu.dnetlib.data.utils;

import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

public class OpenAIREAuthenticationProvider {

	private String authUrl;

	private String clientId;

	private String secret;

	public String obtainAccessToken() {

		final MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
		body.add("grant_type", "client_credentials");

		final HttpHeaders headers = new HttpHeaders();
		headers.set("Authorization", "Basic " + Base64.encodeBase64String((clientId + ":" + secret).getBytes()));

		final ParameterizedTypeReference<Map<String, String>> resType = new ParameterizedTypeReference<Map<String, String>>() {};

		final HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, headers);

		final ResponseEntity<Map<String, String>> res = RestTemplateFactory.newInstance().exchange(authUrl, HttpMethod.POST, httpEntity, resType);

		return res.getBody().get("access_token");

	}

	public String getAuthUrl() {
		return authUrl;
	}

	@Required
	public void setAuthUrl(final String authUrl) {
		this.authUrl = authUrl;
	}

	public String getClientId() {
		return clientId;
	}

	@Required
	public void setClientId(final String clientId) {
		this.clientId = clientId;
	}

	public String getSecret() {
		return secret;
	}

	@Required
	public void setSecret(final String secret) {
		this.secret = secret;
	}

}
