 ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
 
 (ns territory-bro.poller
+  (:refer-clojure :exclude [await])
   (:require [clojure.tools.logging :as log])
   (:import (com.google.common.util.concurrent ThreadFactoryBuilder)
            (java.lang Thread$UncaughtExceptionHandler)
            (java.util Queue)
            (java.util.concurrent ExecutorService Executors TimeUnit ArrayBlockingQueue)))
+
+(defprotocol Poller
+  (trigger! [this])
+  (await [this])
+  (shutdown! [this]))
 
 (def ^:private uncaught-exception-handler
   (reify Thread$UncaughtExceptionHandler

        (when-let [handler (.getUncaughtExceptionHandler t)]
          (.uncaughtException handler t e))))))

(defn trigger! [this]
  (let [executor ^ExecutorService (::executor this)
        available-tasks ^Queue (::available-tasks this)
        task (.poll available-tasks)]
    (when task
      (.execute executor (fn []
                           (.add available-tasks task)
                           (run-safely! task))))))

(defn shutdown! [this]
  (doto ^ExecutorService (::executor this)
    (.shutdown)
    (.awaitTermination 1 TimeUnit/MINUTES)
    (.shutdownNow)))

(defn await [this]
  (let [executor ^ExecutorService (::executor this)
        future (.submit executor ^Runnable (fn []))]
    (.get future)))

      (.setUncaughtExceptionHandler uncaught-exception-handler)
      (.build)))

(defn- run-safely! [task]
  (try
    (task)
