   (:require [reagent.core :as reagent :refer [atom]]
             [re-frame.core :as r]
             [goog.events :as events]
-            [secretary.core :as secretary])
+            [secretary.core :as secretary]
+            [ajax.core :as ajax]
+            [ajax.edn :as edn])
   (:import [goog History]
            [goog.history EventType]))
 
 (def middlewares [(r/path :contents) r/trim-v])
 
+(defn api-request [path callback & {:keys [method params] :or {method :get}}]
+  (ajax/ajax-request
+   (cond-> {:method method
+            :uri (str "/api" path)
+            :handler callback
+            :response-format (edn/edn-response-format)}
+     params (merge {:params params, :format (edn/edn-request-format)}))))
+
 (r/register-handler
  :init
  (fn [_ _]
-   (let [filename "foo"
-         contents {"foo" "foo\nfoo\nfoo"
-                   "bar" "bar\nbar\nbar"
-                   "baz" "baz\nbaz\nbaz"}]
-    {:filename filename
-     :editing-content (get contents filename)
-     :contents contents})))
+   (api-request "/filenames"
+     (fn [[ok? result]]
+       (r/dispatch [:update-filenames (:names result)])))
+   {:filenames nil
+    :filename nil
+    :editing-content nil}))
+
+(r/register-handler
+ :update-filenames
+ [r/trim-v]
+ (fn [db [filenames]]
+   (assoc db :filenames filenames)))
 
 (r/register-handler
  :load-file
  [r/trim-v]
  (fn [db [filename]]
-   (assoc db :filename filename
-             :editing-content (get-in db [:contents filename]))))
+   (api-request (str "/files/" filename)
+     (fn [[ok? result]]
+       (r/dispatch [:show-content filename (:content result)])))
+   db))
+
+(r/register-handler
+ :show-content
+ [r/trim-v]
+ (fn [db [filename content]]
+   (assoc db :filename filename :editing-content content)))
 
 (r/register-handler
  :update-content

    (fn []
      [:ul
       (for [filename @filenames]
         ^{:key filename} [:li [:a {:href (str "#/" filename)} filename]])])))

(defn file-editor []
  (let [file (r/subscribe [:editing-filename])

      (letfn [(on-change [e]
                (r/dispatch [:update-content (.. e -target -value)]))
              (on-blur [e]
                (when @file
                  (r/dispatch [:save-content @file])))]
        [:div
         (when @file
           [:h1 @file])
         [:textarea {:rows 10 :value @content
                     :on-change on-change
                     :on-blur on-blur}]]))))

(defroute "/files/:filename" [filename]
  (r/dispatch [:load-file filename]))

(def history
