 ;; Here, we're setting up basic mongo read and write helpers.
 
 (defn update-export-status
-  [filename document]
+  [filename zinvite document]
   (mc/insert (db/mongo-db (:env/env :mongolab-uri))
              (db/mongo-collection-name "exports")
-             {:filename filename}
+             {:filename filename :zinvite zinvite}
              (db/format-for-mongo identity (assoc document
                                                   :filename filename
+                                                  :zinvite zinvite
                                                   :lastupdate (System/currentTimeMillis)))
              {:upsert true}))
 
 (defn get-export-status
-  [filename]
+  [filename zinvite]
   (mc/find-one (db/mongo-db (:env/env :mongolab-uri))
                (db/mongo-collection-name "exports")
-               {:filename filename}))
+               {:filename filename :zinvite zinvite}))
 
 (defn notify-mongo
   [filename status params]
-  (update-export-status filename {:status status :params params}))
+  (update-export-status filename (:zinvite params) {:status status :params params}))
 
 
 ;; We use AWS to store conversation exports whcih took a long time to compute.

;; completed down the road.

(defn get-status-location-url
  [filename]
  (full-url (str "datadump/status?filename=" filename)))

(defn check-back-response
  ([filename status]
   {:status  status
    :headers {"Content-Type" "text/plain"
              "Location" (get-status-location-url filename)}
    :body    "Request is processing, but cannot be returned now. Please check back later with the same request url."})
  ([filename] (check-back-response 202)))

(defn run-datadump
   "Based on params this actually runs the export-conversation computation."

;; 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)))

