package eu.eudat.logic.security.customproviders.OpenAIRE;

import eu.eudat.logic.security.validators.openaire.helpers.OpenAIREResponseToken;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component("openAIRECustomProvider")
public class OpenAIRECustomProviderImpl implements OpenAIRECustomProvider {

	private Environment environment;

	public OpenAIRECustomProviderImpl(Environment environment) {
		this.environment = environment;
	}

	public OpenAIREUser getUser(String accessToken) {
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = this.createBearerAuthHeaders(accessToken);
		HttpEntity<String> entity = new HttpEntity<>(headers);

		Map<String, Object> values = restTemplate.exchange(this.environment.getProperty("openaire.login.user_info_url"), HttpMethod.GET, entity, Map.class).getBody();
		return new OpenAIREUser().getOpenAIREUser(values);
	}

	public OpenAIREResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret) {
		RestTemplate template = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

		MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

		map.add("grant_type", "authorization_code");
		map.add("code", code);
		map.add("redirect_uri", redirectUri);
		map.add("client_id", clientId);
		map.add("client_secret", clientSecret);
		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

		Map<String, Object> values = template.postForObject(this.environment.getProperty("openaire.login.access_token_url"), request, Map.class);
		OpenAIREResponseToken openAIREResponseToken = new OpenAIREResponseToken();
		openAIREResponseToken.setAccessToken((String) values.get("access_token"));
		openAIREResponseToken.setExpiresIn((Integer) values.get("expires_in"));

		return openAIREResponseToken;
	}

	private HttpHeaders createBearerAuthHeaders(String accessToken) {
		return new HttpHeaders() {{
			String authHeader = "Bearer " + accessToken;
			set("Authorization", authHeader);
		}};
	}
}
