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

import eu.eudat.logic.security.validators.orcid.helpers.ORCIDResponseToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
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("ORCIDCustomProvider")
public class ORCIDCustomProviderImpl implements ORCIDCustomProvider {

    private Environment environment;

    @Autowired
    public ORCIDCustomProviderImpl(Environment environment) {
        this.environment = environment;
    }

    @Override
    public ORCIDResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("accept", "application/json");

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("client_id", this.environment.getProperty("orcid.login.client_id"));
        map.add("client_secret", this.environment.getProperty("orcid.login.client_secret"));
        map.add("grant_type", "authorization_code");
        map.add("code", code);
        map.add("redirect_uri", redirectUri);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

        Map<String, Object> values = restTemplate.postForObject(this.environment.getProperty("orcid.login.access_token_url"), request, Map.class);
        ORCIDResponseToken orcidResponseToken = new ORCIDResponseToken();
        orcidResponseToken.setOrcidId((String) values.get("orcid"));
        orcidResponseToken.setName((String) values.get("name"));
        orcidResponseToken.setAccessToken((String) values.get("access_token"));

        return orcidResponseToken;
    }

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