   "Given aws-creds, returns a function handler function which responds to requests for an existing file on AWS."
   [aws-cred]
   (fn [{:keys [params] :as request}]
-    (let [filename (get params :filename)]
-      (if (= (get (get-export-status filename) "status") "complete")
+    (let [{:keys [filename zinvite]} params]
+      (if (= (get (get-export-status filename zinvite) "status") "complete")
         ;; Have to think about the security repercussions here. Would be nice if we could stream this and never
         ;; expose the link here. XXX
         (redirect-to-aws-url aws-cred filename)

;; Here, we're setting up basic mongo read and write helpers.

(defn update-export-status
  [filename document]
  (mc/insert (db/mongo-db (:env/env :mongolab-uri))
             (db/mongo-collection-name "exports")
             {:filename filename}
             (db/format-for-mongo identity (assoc document
                                                  :filename filename
                                                  :lastupdate (System/currentTimeMillis)))
             {:upsert true}))

(defn get-export-status
  [filename]
  (mc/find-one (db/mongo-db (:env/env :mongolab-uri))
               (db/mongo-collection-name "exports")
               {:filename filename}))

(defn notify-mongo
  [filename status params]
  (update-export-status filename {:status status :params params}))


;; We use AWS to store conversation exports whcih took a long time to compute.

;; Requests for checking the status of a computation

(defn get-datadump-url
  [filename zinvite]
  (full-url (str "datadump/results?filename=" filename "&zinvite=" zinvite)))

(defn complete-response
  [filename zinvite]
  {:status  201
   :headers {"Content-Type" "text/plain"
             "Location"     (get-datadump-url filename zinvite)}
   :body    "Export is complete. Download at the Location url specified in the header"})

(defn get-datadump-status-handler
  [{:keys [params] :as request}]
  (let [{:keys [filename zinvite]} params]
    (case (-> (get-export-status filename zinvite) (get "status"))
      ("pending" "started" "processing") (check-back-response filename zinvite 200)
      "complete"                         (complete-response filename zinvite)
      ;; In case we don't match, 404
      respond-404)))

