              :on-change #(dispatch [:set-username-input (-> % .-target .-value)])}]))
 
 (defn message-form []
-  (let [message  (reagent/atom "")
-        username (subscribe [:username-input])]
+  (let [message   (reagent/atom "")
+        username  (subscribe [:username-input])
+        chat-room (subscribe [:current-chat-room])]
     [:form {:on-submit (fn [e]
+                         ;; prevent redirect
                          (.preventDefault e)
-                         (firebase-swap! @fb-messages conj [@username @message]))}
+                         (dispatch-sync [:send-message @username @message @chat-room])
+                         ;; reset the form
+                         (.reset (.-target e)))}
      [:input {:type "text"
               :on-change #(reset! message (-> % .-target .-value))}]
      [:button {:type "submit"} "Send"]]))

   [message-form]])

(defn join-room-view []
  (let [this-room (atom (random-four-characters))
        change-location #(set! (.-location js/window) (str "#/room/" @this-room))]
    [:div
     [:p [:div
          [:button {:on-click change-location
                    :type "submit"}
           "New Room"]]]

     [:p [:div
          [:input {:placeholder "Room Name"
                   :type "text"
                   :on-change #(reset! this-room (-> % .-target .-value))}]
          [:button {:type "submit"
                    :on-click change-location}
           "Join Room"]]]]))

(defn home-page []
  [:div
   [:div {:class "container"}
    [:div {:class "page-header"}
     [:h2 "Minimal Chat"]]

    (if @chat-room
      [on-going-chat]
      [join-room-view])

    [:div [:br] [:br] [:br]
     "STATE!!!!"
     [:div "Messages: " (pr-str @messages)]]]])

(defn current-page []
  [:div [(session/get :current-page)]])

;; -------------------------
;; Routes

(secretary/defroute "/" []
  (reset! chat-room nil)
  (session/put! :current-page #'home-page))

(secretary/defroute "/room/:id" {:as params}
  (when (not= @chat-room (:id params))
    (join-room (:id params)))
  (session/put! :current-page #'home-page))

;; -------------------------
;; History
;; must be called after routes have been defined

(defn hook-browser-navigation! []
  (doto (History.)

  :username-input
  (fn [db _]
    (reaction (:username @db))))

(register-sub
  :current-chat-room
  (fn [db _]
    (reaction (:chat-room @db))))

(register-sub
  :chat-room-messages
  (fn [db _]
    (reaction (:messages @db))))

;; -- Event Handlers --------

