             (manifold [bus :as bus]
                       [deferred :as d]
                       [stream :as s])
+            [throttle.core :as throttle]
             [metabase.db :as db]
             [metabase.integrations.slack :as slack]
             [metabase.models.setting :refer [defsetting], :as setting]


;;; Websocket monitor

;; Keep track of the Thread ID of the current monitor thread. Monitor threads should check this ID and if it is no longer equal to
;; theirs they should die
(defonce ^:private websocket-monitor-thread-id (atom nil))

(defn- start-websocket-monitor! []
  (future
    (reset! websocket-monitor-thread-id (.getId (Thread/currentThread)))
    ;; Every 2 seconds check to see if websocket connection is [still] open, [re-]open it if not
    (loop []
      (Thread/sleep 500)
      (when (= (.getId (Thread/currentThread)) @websocket-monitor-thread-id)
        (try
          (when (or (not  @websocket)
                    (s/closed? @websocket))
            (log/debug "MetaBot WebSocket is closed.  Reconnecting now.")
            (connect-websocket!))
          (catch Throwable e
            (log/error "Error connecting websocket:" (.getMessage e))))


   This will spin up a background thread that opens and maintains a Slack WebSocket connection."
  []
  (when (and (slack/slack-token)
             (metabot-enabled))
    (log/info "Starting MetaBot WebSocket monitor thread...")
    (start-websocket-monitor!)))
