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;
import io.ljunggren.usps.api.model.Debug;
import io.ljunggren.usps.api.model.HttpStatusCode;

public class OauthService extends BaseService {

    public OauthService(String domain) {
        super(domain);
    }

    private final String URI = domain + "/oauth2/v3/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);
        try {
            post.setEntity(new UrlEncodedFormEntity(parameters));
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (HttpStatusCode.THROTTLING.getCode() == responseCode) {
                    throw429();
                }
                if (HttpStatusCode.SERVICE_UNAVAILABLE.getCode() == responseCode) {
                    throw new Exception("USPS API not found");
                }
                String json = getResult(response);
                checkForError(responseCode, json);
                return JsonUtils.jsonToObject(json, AuthToken.class);
            }
        } finally {
            httpClient.close();
        }
    }

    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));
        Debug debug = debug(post, httpClient, new Debug());
        redactAccessToken(debug);
        return debug;
    }

    private void redactAccessToken(Debug debug) {
        String response = debug.getResponse();
        if (response == null) {
            return;
        }
        try {
            AuthToken token = JsonUtils.jsonToObject(response, AuthToken.class);
            if (token.getAccessToken() != null) {
                token.setAccessToken("***REDACTED***");
                debug.setResponse(JsonUtils.objectToJson(token));
            }
        } catch (Exception e) {
            // Not a token response (e.g. an error body) - leave as-is.
        }
    }
    
    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),
        });
    }

}
