 (ns appengine-magic.services.urlfetch
-  (:import [com.google.appengine.api.urlfetch URLFetchServiceFactory]))
+  (:import [com.google.appengine.api.urlfetch
+            URLFetchServiceFactory
+            FetchOptions
+            FetchOptions$Builder
+            HTTPRequest
+            HTTPMethod])
+  (:require [clojure.contrib.string :as string]))
 
 (defonce *urlfetch-service* (atom nil))
 

		 (parse-headers (.getHeaders r))
		 (.getResponseCode r)))

(defn fetch [url]
  (parse-response (.fetch (get-urlfetch-service) (urlify url))))

(defn fetch-async [url]
  (let [f (.fetchAsync (get-urlfetch-service) (urlify url))]
    (reify
     clojure.lang.IDeref
      (deref [_] (parse-response (.get f)))

  (zipmap (map #(keyword (.getName %)) headers)
	  (map #(.getValue %) headers)))

(defn- make-headers [header-map]
  (map
   (fn [[name-key val]]
     (com.google.appengine.api.urlfetch.HTTPHeader.
      (string/as-str name-key)
      val))
   header-map))

(defn- parse-response
  [^com.google.appengine.api.urlfetch.HTTPResponse r]
  (HTTPResponse. (.getContent r)
