package org.gbif.occurrence.query;

import org.gbif.utils.HttpUtil;

import com.google.inject.Inject;
import com.google.inject.PrivateModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import com.sun.jersey.client.apache4.ApacheHttpClient4Handler;
import org.apache.http.client.HttpClient;

/**
 * Guice module providing a TitleLookup instance for the HumanFilterBuilder to lookup species and dataset titles.
 */
public class TitleLookupModule extends PrivateModule {
  private final boolean provideHttpClient;
  private final String apiRoot;

  /**
   * @param provideHttpClient if true the module creates a new internal only http client instance
   */
  public TitleLookupModule(boolean provideHttpClient, String apiRoot) {
    this.provideHttpClient = provideHttpClient;
    this.apiRoot = apiRoot;
  }

  @Override
  protected void configure() {
    if (provideHttpClient) {
      bind(HttpClient.class).toInstance(provideHttpClient());
    }
    expose(TitleLookup.class);
  }

  @Provides
  @Singleton
  @Inject
  public TitleLookup provideLookup(HttpClient hc) {
    ApacheHttpClient4Handler hch = new ApacheHttpClient4Handler(hc, null, false);
    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    WebResource api = new ApacheHttpClient4(hch, clientConfig).resource(apiRoot);
    return new TitleLookup(api);
  }

  private HttpClient provideHttpClient() {
    return HttpUtil.newMultithreadedClient(5000, 10, 10);
  }
}

@@ -62,16 +62,83 @@
 pUtil;%0A%0A
+import java.net.URI;%0A%0Aimport com.google.common.base.Preconditions;%0A
 import c
@@ -162,16 +162,16 @@
 Inject;%0A
-
 import c
@@ -644,16 +644,73 @@
 pClient;
+%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;
 %0A%0A/**%0A *
@@ -880,16 +880,102 @@
 odule %7B%0A
+  private static final Logger LOG = LoggerFactory.getLogger(TitleLookupModule.class);%0A
   privat
@@ -1025,22 +1025,19 @@
 e final 
-String
+URI
  apiRoot
@@ -1288,23 +1288,252 @@
 iRoot = 
-apiRoot
+URI.create(Preconditions.checkNotNull(apiRoot, %22API url can't be null%22));%0A    Preconditions.checkArgument(this.apiRoot.getHost()!=null, %22API url must have a host! %22 + apiRoot);%0A    LOG.info(%22Create new TitleLookup using API %22 + apiRoot)
 ;%0A  %7D%0A%0A 
@@ -2246,14 +2246,15 @@
 0, 10);%0A
-
   %7D%0A
+%0A
 %7D%0A

Verify api root config in module constructor