 (ns ^{:doc "Render the views for the application."}
   one.repmax.view
-  (:use [domina :only (append! by-id destroy-children! set-attr! set-html! set-text! swap-content!)]
-        [domina.xpath :only (xpath)])
+  (:use [domina.xpath :only (xpath)])
   (:require-macros [one.repmax.snippets :as snippets])
-  (:require [one.dispatch :as dispatch]))
+  (:require [one.dispatch :as dispatch]
+            [domina :as d]))
 
 (def ^{:doc "A map which contains chunks of HTML which may be used
   when rendering views."}

  :state)

(defmethod render :exercise-list [_]
  (let [header (by-id "header")
        content (by-id "content")]
    (swap-content! header (:exercises-header snippets))
    (set-html! content (:exercises-search snippets))
    (append! content (:exercises-list snippets))))

(dispatch/react-to #{:state-change} (fn [_ m] (render m)))


(defn- render-exercise-list [exercises]
  (let [content (xpath "//div[@id='exercise-list']/ol")]
    (d/destroy-children! content)
    (doseq [e exercises]
      (d/append! content (exercise-list-item e)))))

(defn- exercise-list-item [exercise]
  (let [li (d/clone (:exercises-list-item snippets))
        dom-id (str "exercise-" (:_id exercise))]
    (-> li
      (d/set-attr! "id" dom-id))
    (-> li (xpath "a")
      (d/set-attr! "href" (str "#")))
    (-> li (xpath ".//span[@class='list-item-label']")
      (d/set-text! (:name exercise)))
    li))

(dispatch/react-to #{:exercise-search-results-ready}
