             [aleph.http :as http])
   (:gen-class))
 
-(defn refresh-backend-watcher [watcher old-prefix new-prefix]
-  (if (and watcher (= old-prefix new-prefix))
-    watcher
-    (do (if watcher (close! watcher))
-        (etcd/watch-prefix new-prefix))))
 (defn spy [a] (pprint a) a)
 
 (defn proxy-handler1 [backends-ch req]

(defn healthy-backend?
  "true if backend seen more recently than time"
  [time b]
  (> (s->millepoch-time (:last-seen-at b))
     time))

(defn run-server [prefix]
  (let [shutdown-ch (chan)
        config-watcher (etcd/watch-prefix prefix)
        backends-ch (chan)]
    (go
      (loop [listeners {}
             backends {}
             backend-prefix nil
             backend-watcher nil]
        (let [config (etcd/get-prefix prefix)
              new-bp (:upstream-service-etcd-prefix config)
              backends (if new-bp
                         (update-backends-from-config
                          backends (etcd/get-prefix new-bp))
                         backends)
              listeners (update-listeners-from-config
                         backends-ch
                         listeners
                         (:listen-address config))]
          (print-state listeners backends)
          (let [[value ch]
                (alts! (remove nil?
                               [config-watcher
                                backend-watcher
                                shutdown-ch
                                backends-ch]))]
            (when (= ch backends-ch)
              (let [since (- (millepoch-time-now)
                             (* 1000 (Integer/parseInt (:upstream-freshness config))))
                    good-backends (filter (partial healthy-backend? since)
                                          (vals backends))]
                (if (seq good-backends)
                  (alts! (map (fn [b] [(:channel b) value]) good-backends))
                  (>! (second value) {:status 500 :headers {}
                                      :body "No healthy downstreams"}))))
            (if (= ch shutdown-ch)
              (.close (first (vals listeners)))
              (recur listeners
                     backends
                     new-bp
                     (refresh-backend-watcher backend-watcher backend-prefix new-bp))))))
      (println "quit"))
    shutdown-ch))





(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (println "Hello, World!")
;  (add-watch etcd/configuration :update-frontend update-frontend)
;  (etcd/watch-config (first args))
  (println "running"))

      (println [:shutdown backend]))
    ch))

(defn s->millepoch-time [s]
  (.getTimeInMillis (clojure.instant/read-instant-calendar s)))

