package com.metabroadcast.atlas.glycerin;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.apache.ApacheHttpTransport;
import com.google.common.net.HostSpecifier;

class GlycerinHttpClient {

    private final Logger log = LoggerFactory.getLogger(getClass());
    
    private final HostSpecifier host;
    private final String apiKey;
    
    private final HttpRequestFactory requestFactory;

    public GlycerinHttpClient(HostSpecifier host, String apiKey) {
        this.host = checkNotNull(host);
        this.apiKey = checkNotNull(apiKey);
        this.requestFactory = new ApacheHttpTransport()
            .createRequestFactory(new HttpRequestInitializer() {
                @Override
                public void initialize(HttpRequest request) {
                    request.setParser(new JaxbObjectParser(new NitroJaxbContext().getContext()));
                }
            });
    }
    
    public <R, T> GlycerinResponse<T> get(GlycerinQuery<R, T> q) throws IOException {
        HttpRequest getRequest = requestFactory.buildGetRequest(urlFor(q));
        log.debug("{}", getRequest.getUrl());
        return q.toResponse(getRequest.execute().parseAs(q.type()));
    }
    
    private GenericUrl urlFor(GlycerinQuery<?, ?> q) {
        GenericUrl url = new GenericUrl();
        url.setScheme("http");
        url.setHost(host.toString());
        url.set("api_key", apiKey);
        url.setRawPath(q.resourcePath());
        url.putAll(q.queryParameters());
        return url;
    }

}

@@ -235,16 +235,155 @@
 ricUrl;%0A
+import com.google.api.client.http.HttpBackOffIOExceptionHandler;%0Aimport com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;%0A
 import c
@@ -421,16 +421,16 @@
 equest;%0A
-
 import c
@@ -595,16 +595,70 @@
 nsport;%0A
+import com.google.api.client.util.ExponentialBackOff;%0A
 import c
@@ -722,16 +722,162 @@
 ient %7B%0A%0A
+    private static final ExponentialBackOff BACK_OFF = new ExponentialBackOff.Builder()%0A        .setInitialIntervalMillis(500)%0A        .build();%0A%0A
     priv
@@ -1369,16 +1369,16 @@
 verride%0A
-
         
@@ -1427,24 +1427,234 @@
  request) %7B%0A
+                    request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(BACK_OFF));%0A                    request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(BACK_OFF));%0A
             

add unconfigurable exponential backoff