             [ring.adapter.jetty :refer [run-jetty]]
             [hiccup.page :as page]
             [hiccup.form :as form]
-            [hiccup.util :as util]))
+            [hiccup.util :as util]
+            [ring.util.response :refer [redirect]]))
+
+; State
+
+(def posts (ref {}))
+(def nextId (ref 1))
+
+; Post form
 
 (defn page-layout [title & body]
   (page/html5

(defroutes routes
  (resources "/")
  (resources "/react" {:root "react"})
  (GET "/" [_] (post-form))
  (POST "/" [code] (show-code code))
  (GET "/*" req (page)))

(def http-handler
  (if is-dev?

      body]
     (page/include-js "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js")]))

(defn show-code [id]
  (let [code (get @posts (read-string id))]
    (if code
      (code-layout
        (str "Fragment " id)
        [:h1 (str "Fragment " id)]
        [:pre
         [:code (util/escape-html code)]])
      (page-layout
        "Unexisten fragment"
        [:div {:class "alert alert-danger" :role "alert"} "Unexistent fragment"]))))

(defn post-code [code]
  (dosync
    (alter posts assoc @nextId code)
    (alter nextId inc))
  (redirect "/"))

; Show list of posts

(defn show-posts []
  (page-layout
    "List of fragments"
    [:h1 "List of fragments"]
    [:ul
     (for [k (reverse (sort (keys @posts)))]
       [:li [:a {:href (str "/posts/" k)} (str "Fragment " k)]])]))

(deftemplate page
  (io/resource "index.html") [] [:body] (if is-dev? inject-devmode-html identity))
