              assoc-in
              [game-id :players chan-id]
              (assoc socket-user :color (:player/color player))))))
+
+(defn- leave-game
+  [_]
+  (fn [{:keys [chan-id] :as socket-user}
+      {:keys [game-id]}]
+    (remove-chan-form-room game-id chan-id)))
 
 (defn- broadcast-game-message
   [game-id formatted-message]

  {:keep-alive keep-alive
   :handshake (handshake datomic)
   :join-game (join-game datomic)
   :authenticate-user (authenticate-user datomic)
   :chat-message (chat-message datomic)})


            [io.pedestal.http.jetty.websockets :as ws]))

(def ^:private game-rooms (atom {}))
(def ^:private connections (atom {}))

(defn- remove-chan-form-room
  [game-id chan-id]
  (swap! game-rooms update-in [game-id :players] dissoc chan-id))

(defn- cleanup-closed-connections
  []
  (doseq [[chan-id {:keys [session]}] @connections]
    (let [channel-open? (.isOpen session)]
      (when-not channel-open?
        ;; Remove channel from game rooms
        (map (fn [game-id {players :players}]
               (let [contains-connection? (chan-id players)]
                 (when contains-connection?
                   (remove-chan-form-room game-id chan-id))))
             @game-rooms)
        ;; Remove channel from connections
        (swap! connections dissoc chan-id)))))

(defn- cleanup-empty-games
  []
  (doseq [[game-id {:keys [players]}] @game-rooms]
    (let [game-empty? (= (count players) 0)]
      (when game-empty?
        (swap! game-rooms dissoc game-id)))))

(defn clean-connections
  "Removes all closed connections from state"
  [time]
  (cleanup-closed-connections)
  (cleanup-empty-games))

(defn connection-clean-err
  "If the scheduler fails this will be called
