package com.braintree.commands.impl;

import com.braintree.hybris.data.BrainTreeConnectWithPayPalUserData;
import de.hybris.platform.payment.AdapterException;
import de.hybris.platform.payment.commands.Command;
import org.apache.log4j.Logger;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;


public class DefaultBrainTreeConnectWithPayPalGetUserInformationCommand extends AbstractCommand implements
    Command<String, BrainTreeConnectWithPayPalUserData> {

    private static final Logger LOG = Logger.getLogger(DefaultBrainTreeConnectWithPayPalGetUserInformationCommand.class);

    private static final String USER_INFO_ENDPOINT_URL = "identity/oauth2/userinfo?schema=paypalv1.1";
    private static final String ERROR_MESSAGE = "Error during try exchange authorization token to access token";

    private RestTemplate restTemplate;

    @Override
    public BrainTreeConnectWithPayPalUserData perform(String accessToken){
        HttpHeaders headers = new HttpHeaders();
        String endpointUrl = getBrainTreeConfigService().getPayPalApiUrl().concat(USER_INFO_ENDPOINT_URL);
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(accessToken);
        HttpEntity<LinkedMultiValueMap<String, String>> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<BrainTreeConnectWithPayPalUserData> response;
        try {
            response = restTemplate
                .exchange(endpointUrl, HttpMethod.GET, httpEntity, BrainTreeConnectWithPayPalUserData.class);
        } catch (Exception e) {
            LOG.error(ERROR_MESSAGE, e);
            throw new AdapterException(e.getMessage());
        }
        return response.getBody();
    }

    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
}
