package io.ljunggren.usps.api.service;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.Arrays;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;

import io.ljunggren.usps.api.model.Debug;
import io.ljunggren.usps.api.model.address.Address;
import io.ljunggren.usps.api.model.address.AddressResponse;

public class AddressService extends BaseService {

    public AddressService(String domain) {
        super(domain);
    }
    
    private final String URI = domain + "/addresses/v3/address";
    
    public AddressResponse validate(Address address, String accessToken) throws Exception {
        return validate(address, accessToken, getHttpClient());
    }

    public AddressResponse validate(Address address, String accessToken, CloseableHttpClient httpClient) throws Exception {
        try {
            HttpGet get = new HttpGet(buildUri(address));
            get.setHeaders(generateHeaders(accessToken));
            CloseableHttpResponse response = httpClient.execute(get);
            int responseCode = response.getStatusLine().getStatusCode();
            if (responseCode ==  429) {
                throw429();
            }
            String json = getResult(response);
            return parse(json, AddressResponse.class);
        } finally {
            httpClient.close();
        }
    }
    
    private String buildUri(Address address) throws URISyntaxException {
    	return new URIBuilder(URI)
                .addParameters(Arrays.asList(new NameValuePair[] {
                        new BasicNameValuePair("streetAddress", address.getStreetAddress()),
                        new BasicNameValuePair("secondaryAddress", address.getSecondaryAddress()),
                        new BasicNameValuePair("city", address.getCity()),
                        new BasicNameValuePair("state", address.getState()),
                        new BasicNameValuePair("ZIPCode", address.getZipCode()),
                })).toString();
    }
    
    public Debug debug(Address address, String accessToken) throws Exception {
        HttpGet get = new HttpGet(buildUri(address));
        get.setHeaders(generateHeaders(accessToken));
    	return debug(get, getHttpClient(), new Debug());
    }

    private Header[] generateHeaders(String accessToken) throws UnsupportedEncodingException {
        return new Header[] { 
                new BasicHeader("Authorization", "Bearer " + accessToken) 
        };
    }
    
}
