package io.ljunggren.geoapify.api.service;

import java.net.URI;
import java.util.Arrays;
import java.util.List;

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.BasicNameValuePair;

import io.ljunggren.geoapify.api.model.response.Response;

public class PostalCodeService extends BaseService {
    
    private final String URI = domain + "/v1/postcode/search";
    
    public PostalCodeService(String apiKey) {
        super(apiKey);
    }
    
    public Response lookup(String postalCode, String countryCode) throws Exception {
        return lookup(postalCode, countryCode, getHttpClient());
    }
    
    public Response lookup(String postalCode, String countryCode, CloseableHttpClient httpClient) throws Exception {
        List<NameValuePair> parameters = generateParameters(postalCode, countryCode == null ? null : countryCode.toLowerCase());
        URI uri = new URIBuilder(URI)
                .setParameters(parameters)
                .build();
        HttpGet get = new HttpGet(uri.toString());
        try {
            CloseableHttpResponse response = httpClient.execute(get);
            String json = getResult(response);
            return parse(json, Response.class);
        } finally {
            httpClient.close();
        }
    }

    private List<NameValuePair> generateParameters(String postalCode, String countryCode) {
        return Arrays.asList(new BasicNameValuePair[] {
                new BasicNameValuePair("apiKey", apiKey),
                new BasicNameValuePair("postcode", postalCode),
                new BasicNameValuePair("countrycode", countryCode)
        });
    }

}
