(ns wanijo.infrastructure.devmode
  (:require [hiccup.core :as hcore]
            [clojure.string :as cljs]))

(def bar-entries (atom []))

(defn send-to-bar [msg]
  (swap! bar-entries #(conj % msg)))

(defn devmode-on? [req]
  (let [query-param (get-in req [:query-params "dev"])
        cookie (get-in req [:cookies "devmode" :value])]
    (or (= query-param "on")
        (and (= cookie "1")
             (not= query-param "off")))))

(defn devbar [resp]
  (hcore/html
   [:section.devbar
    [:ol
     (for [entry @bar-entries]
       [:li [:pre entry]])]]))

(defn append-devbar [resp]
  (let [body (:body resp)
        new-body (cljs/replace
                  body "</body>" (str (devbar resp) "</body>"))]
    (assoc resp :body new-body)))

(defn wrap-devmode [handler]
  (fn [req]
    (let [on? (devmode-on? req)
          query-param? (get-in req [:query-params "dev"])
          new-req (assoc-in req [:session :devmode] on?)
          resp (handler new-req)
          new-resp (cond
                     on? (-> resp
                             append-devbar
                             (assoc-in [:cookies :devmode] 1))
                     (some? query-param?) (assoc-in
                                           resp
                                           [:cookies :devmode]
                                           (if on? 1 0))
                     :else resp)]
      (reset! bar-entries [])
      new-resp)))
