(ns pubsub.demo
  (:require [bidi.ring :refer [make-handler resources-maybe]]
            [ring.middleware.json :refer [wrap-json-response wrap-json-body]]
            [ring.util.response :refer [response]]
            ))

(defn init []
  (comment "-use mesos disco for kafka and zookeeper URLs")
  (println "Hello! Init done."))



(def messages (atom {}))

(defn produce
  [req]
  (let [{channel :channel} (:route-params req)
        body (:body req)
        channel-messages (conj (get @messages channel []) body)]
    (println "produced body:" body)
    (swap! messages assoc channel channel-messages)
    {:status 200 :body {:latest-offset (count channel-messages)
                        :avail (keys req)}}))

(clojure.tools.nrepl.middleware.interruptible-eval)

(defn consume
  [req]
  (println "consume")
  (let [{channel :channel offset :offset count_ :count} (:route-params req)
        channel-messages (get @messages channel [])
        messages (subvec channel-messages (Long/valueOf offset) (Long/valueOf count_))]
    {:status 200 :body {:messages messages}}))


(def pubsub-routes ["/" {["produce/" :channel] {:put produce}
                         ["consume/" :channel "/" :offset "/" :count] {:get consume}
                         "" (resources-maybe {:prefix "public/"})}])


(def app (-> (make-handler pubsub-routes)

             ; todo support EDN. implement these to mirror json. ie use body, not params.
             ;wrap-edn-body
             ;wrap-edn-response

             wrap-json-body
             wrap-json-response))
