 (def apps
   {:chat {:link "/chat"}})
 
+
 (declare channels threads messages)
+
+(defn geoFromText [lon lat]
+  (str "ST_GeographyFromText('SRID=4326;POINT(" lon " " lat ")')"))
+
+(defn get-channels [lon lat]
+  (korma/select channels
+    (korma/where
+      (korma/raw (str "ST_DWithin(location," (geoFromText lon lat) ",200)")))))
+
+(defn add-channel [channel-name lon lat]
+  (korma/insert channels
+    (korma/values
+      {:name channel-name
+       :location (korma/raw (geoFromText lon lat))})))
+
+(defn get-threads [channel-id]
+  (korma/select threads
+    (korma/where {:channel_id channel-id})))
+
+(defn add-chat-thread [channel-id thread-descr]
+  (korma/insert threads
+    (korma/values {:channel_id channel-id
+                   :description thread-descr})))
+
+(defn get-messages [channel-id thread-id]
+  (korma/select messages
+    (korma/where {:channel_id channel-id
+                  :thread_id thread-id})))
+
+(defn add-msg [channel-id thread-id msg]
+  (korma/insert messages
+    (korma/values {:channel_id channel-id
+                   :thread_id thread-id
+                   :message msg})))
+
 
 (defn edn-response [body]
   {:status 200
    :headers {"Content-Type" "application/edn"}
    :body (pr-str body)})
 
-(defn geoFromText [lon lat]
-  (str "ST_GeographyFromText('SRID=4326;POINT(" lon " " lat ")')"))
-
 (defn apps-handler [request]
   (edn-response apps))
-
-(defn get-channels [lon lat]
-  (korma/select channels
-    (korma/where
-      (korma/raw (str "ST_DWithin(location," (geoFromText lon lat) ",200)")))))
 
 (defn channels-handler [request]
   (edn-response

                                   :password "postgres"}))

  (korma/defentity channels
    (korma/table :channels)
    (korma/transform
      (fn [c] (-> c
                  (assoc :app :chat)

          lat (Double/parseDouble (:lat params))]
      (get-channels lon lat))))

(defn new-channel-handler [request]
  (edn-response
    (let [body (read-string (slurp (:body request)))
          geolocation (:geolocation body)]
      (add-channel (:channel-name body) (:lon geolocation) (:lat geolocation)))))

(defn chat-threads-handler [request]
  (edn-response
