/*
 * Copyright (C) 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.api.explorer.client.base.http.crossdomain;

import com.google.api.explorer.client.base.ApiRequest;
import com.google.api.explorer.client.base.ApiResponse;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.ScriptElement;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Builds requests to make to an cross-domain proxy iframe.
 *
 * <p>
 * This consists of adding a <script> tag to the page to load the JS library to
 * make cross-domain requests to the server.
 * </p>
 *
 * @author jasonhall@google.com (Jason Hall)
 */
public class CrossDomainRequestBuilder {

  private static final String JS_CLIENT_NAME = "ae_f85e3bd0744c7080861c3ae42085d071.js";
  private static final String JS_CLIENT_URL = "https://ssl.gstatic.com/gb/js/" + JS_CLIENT_NAME;

  private int timeoutMillis;

  private static native boolean scriptLoaded() /*-{
    return !!$wnd.googleapis && !!$wnd.googleapis.newHttpRequest;
  }-*/;

  public void setTimeoutMillis(int timeoutMillis) {
    this.timeoutMillis = timeoutMillis;
  }

  public CrossDomainRequest makeRequest(
      final ApiRequest request, AsyncCallback<ApiResponse> callback) {
    final CrossDomainRequest xdr = new CrossDomainRequest(callback, timeoutMillis);

    /** Adds a script tag to the page to load the JS library used to make requests. */
    if (!scriptLoaded()) {
      ScriptElement script = Document.get().createScriptElement();
      script.setSrc(JS_CLIENT_URL);
      Document.get().getElementsByTagName("head").getItem(0).appendChild(script);

      new Timer() {
        @Override
        public void run() {
          if (scriptLoaded()) {
            setBaseUrl();
            doMakeRequest(request, xdr);
            cancel();
          }
        }
      }.scheduleRepeating(100);
    } else {
      doMakeRequest(request, xdr);
    }
    return xdr;
  }

  private <T> void doMakeRequest(ApiRequest request, final CrossDomainRequest xdr) {
    JavaScriptObject jso = CrossDomainRequest.convertRequest(request);
    xdr.sendRequest(jso);
  }

  private static native void setBaseUrl() /*-{
    var proxy = @com.google.api.explorer.client.base.Config::baseUrl + '/static/proxy.html';
    $wnd['__GOOGLEAPIS'] = {
      'googleapis.config': {
        'proxy': proxy,
        'gcv':
            @com.google.api.explorer.client.base.http.crossdomain.CrossDomainRequestBuilder::JS_CLIENT_NAME
      }
    };
  }-*/;
}

@@ -797,32 +797,24 @@
 .client.
-JavaScriptObject
+Callback
 ;%0Aimport
@@ -833,62 +833,20 @@
 gwt.
-dom.client.Document;%0Aimport com.google.gwt.dom
+core
 .client.
 Scri
@@ -841,28 +841,31 @@
 .client.
+Java
 Script
-Elemen
+Objec
 t;%0Aimpor
@@ -881,28 +881,28 @@
 gle.gwt.
-user
+core
 .client.
 Timer;%0Ai
@@ -893,20 +893,29 @@
 .client.
-Time
+ScriptInjecto
 r;%0Aimpor
@@ -2032,282 +2032,131 @@
 ript
-Element script = Document.get().createScriptElement();%0A      script.setSrc(JS_CLIENT_URL);%0A      Document.get().getElementsByTagName(%22head%22).getItem(0).appendChild(script);%0A%0A      new Timer() %7B%0A        @Override%0A        public void run() %7B%0A          if (scriptLoaded()
+Injector.fromUrl(JS_CLIENT_URL).setCallback(new Callback%3CVoid, Exception%3E() %7B%0A        public void onSuccess(Void result
 ) %7B%0A
-  
     
@@ -2171,26 +2171,24 @@
 tBaseUrl();%0A
-  
           do
@@ -2226,73 +2226,123 @@
     
+%7D%0A%0A
     
-cancel();%0A          %7D%0A        %7D%0A      %7D.scheduleRepeating(100
+    public void onFailure(Exception e) %7B%0A          throw new RuntimeException(e);%0A        %7D%0A      %7D).inject(
 );%0A 

Use GWT 2.4's ScriptInjector instead of injecting scripts ourselves.