package io.ljunggren.fedex.api.service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;

import io.ljunggren.fedex.api.authorization.AuthToken;
import io.ljunggren.fedex.api.model.Debug;

public class OauthService extends BaseService {

    private static final int MAX_ATTEMPTS = 3;
    private static final long RETRY_BACKOFF_MS = 1000;

    public OauthService(String domain) {
        super(domain);
    }

    private final String URI = domain + "/oauth/token";

    public AuthToken authorize(String clientId, String clientSecret) throws Exception {
        return authorize(clientId, clientSecret, getHttpClient());
    }

    public AuthToken authorize(String clientId, String clientSecret, CloseableHttpClient httpClient) throws Exception {
        HttpPost post = new HttpPost(URI);
        List<NameValuePair> parameters = generateParameters(clientId, clientSecret);
        post.setEntity(new UrlEncodedFormEntity(parameters));
        IOException lastFailure = null;
        try {
            for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
                try (CloseableHttpResponse response = httpClient.execute(post)) {
                    String json = getResult(response);
                    return parse(json, AuthToken.class);
                } catch (IOException e) {
                    lastFailure = e;
                    if (attempt < MAX_ATTEMPTS) {
                        Thread.sleep(RETRY_BACKOFF_MS * attempt);
                    }
                }
            }
        } finally {
            httpClient.close();
        }
        throw lastFailure;
    }
    
    public Debug debug(String clientId, String clientSecret) throws Exception {
        return debug(clientId, clientSecret, getHttpClient());
    }
    
    public Debug debug(String clientId, String clientSecret, CloseableHttpClient httpClient) throws Exception {
        HttpPost post = new HttpPost(URI);
        List<NameValuePair> parameters = generateParameters(clientId, clientSecret);
        post.setEntity(new UrlEncodedFormEntity(parameters));
    	return debug(post, httpClient);
    }
    
    private List<NameValuePair> generateParameters(String clientId, String clientSecret) {
        return Arrays.asList(new BasicNameValuePair[] {
                new BasicNameValuePair("grant_type", "client_credentials"),
                new BasicNameValuePair("client_id", clientId),
                new BasicNameValuePair("client_secret", clientSecret)
        });
    }

}
