             [ring.middleware.params :as params]
             [bidi.bidi :as bidi]
             [cheshire.core :as json]
+            [clj-time.core :as t]
             [build-mon.vso-api :as api]
             [build-mon.vso-release-api :as release-api]
             [build-mon.html :as html])
   (:gen-class))
 
 (def logger {:log-exception (fn [message exception]
-                              (prn "=========   ERROR   ==========")
-                              (prn message)
-                              (prn exception)
-                              (prn "=============================="))})
+                              (println "=========   ERROR   ==========")
+                              (println message)
+                              (println exception)
+                              (println "=============================="))})
 
 (def states-ordered-worst-first [:failed :in-progress-after-failed :in-progress :succeeded])
 

(defn in-progress? [build] (nil? (:result build)))

(defn- get-release-state [release-env previous-release-env]
    (cond (release-succeeded? release-env) :succeeded
          (and (release-in-progress? release-env) (release-succeeded? previous-release-env)) :in-progress
          (and (release-in-progress? release-env) (not (release-succeeded? previous-release-env))) :in-progress-after-failed
          (release-not-started? release-env) :not-started
          :default :failed))

(defn get-state [build previous-build]
  (cond (succeeded? build) :succeeded

        build-definition-ids (map :id build-definitions)]
    (universal-monitor-for-definition-ids vso-api vso-release-api request build-definition-ids release-definition-ids)))

(def routes ["/" :universal-monitor])

(defn wrap-routes [handlers]
  (fn [request]
    (let [request-start-time (t/now)]
      (when-let [route (bidi/match-route routes (:uri request))]
        (when-let [handler (-> route :handler handlers)]
          (let [response (handler (merge request (select-keys route [:route-params])))]
            (println "Response time:" (t/in-seconds (t/interval request-start-time (t/now))) "seconds")
            response))))))

(defn handlers [vso-api vso-release-api]
  {:universal-monitor (partial universal-monitor vso-api vso-release-api)})
