 (ns pc.server
-  (:require [clojure.tools.logging :as log]
+  (:require [clojure.core.async :as async]
+            [clojure.tools.logging :as log]
             [clojure.tools.reader.edn :as edn]
             [clj-time.core :as time]
             [compojure.core :refer (defroutes routes GET POST ANY)]

   (GET "/" [] (content/app))
   (compojure.route/resources "/" {:root "public"
                                   :mime-types {:svg "image/svg"}})
   (GET "/chsk" req ((:ajax-get-or-ws-handshake-fn sensa-fns) req))
   (POST "/chsk" req ((:ajax-post-fn sensa-fns) req))
   (ANY "*" [] {:status 404 :body nil})))

(defn port []


(defn restart []
  (stop)
  (start @senta-state))

(defn user-id-fn [ring-req]
  (println "calling user-id-fn")
  (println (get-in ring-req [:params :test]))
  (get-in ring-req [:params :test]))

(defn ws-handler [req]
  (def req req)
  (log/info (:event req)))

(defn setup-ws-handlers [senta-state]
  (let [tap (async/chan (async/sliding-buffer 100))
        mult (async/mult (:ch-recv senta-state))]
    (async/tap mult tap)
    (async/go-loop []
                   (when-let [req (async/<! tap)]
                     (ws-handler req)
                     (recur)))))

(defn senta-init []
  (let [{:keys [ch-recv send-fn ajax-post-fn connected-uids
                ajax-get-or-ws-handshake-fn] :as fns} (sente/make-channel-socket! {:user-id-fn #'user-id-fn})]
    (reset! senta-state fns)
    (setup-ws-handlers fns)))

(defn init []
  (senta-init)
  (start @senta-state))
