package io.ljunggren.usps.api.service;

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.json.utils.JsonUtils;
import io.ljunggren.usps.api.authorization.AuthToken;

public class OauthService extends BaseService {

    public OauthService(String domain) {
        super(domain);
    }
    
    private final String URI = domain + "/oauth2/v3/token";
    
    public AuthToken authorize(String cliendId, String clientSecret) throws Exception {
        return authorize(cliendId, clientSecret, getHttpClient());
    }

    public AuthToken authorize(String clientId, String clientSecret, CloseableHttpClient httpClient) throws Exception {
        HttpPost post = new HttpPost(URI);
        List<NameValuePair> parameters = generateParameters(clientId, clientSecret);
        try {
            post.setEntity(new UrlEncodedFormEntity(parameters));
            CloseableHttpResponse response = httpClient.execute(post);
            int responseCode = response.getStatusLine().getStatusCode();
            if (responseCode ==  429) {
                throw429();
            }
            if (responseCode == 503) {
            	throw new Exception("USPS API not found");
            }
            String json = getResult(response);
            return JsonUtils.jsonToObject(json, AuthToken.class);
        } finally {
            httpClient.close();
        }
    }
    
    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),
        });
    }

}
