 (defn bounding-box
   ([node] (bounding-box @current-automation node))
   ([{c :connection :as ctx} node]
-   (let [{:keys [width height content]} (:model (dom/get-box-model c node))
+   (let [node (to-node-ref ctx node)
+         {:keys [width height content]} (:model (dom/get-box-model c node))
          [x y] content]
      {:x x :y y
       :width width :height height

        ;; :value only works for simple values
        :result :value)))

(comment
  (defn scroll-visible
    "Make the given node visible by scrolling to it. Returns the bounding box in
  screen coordinates (NOT page).
  Tries to center the viewport around the element."
    ([node] (scroll-visible @current-automation node))
    ([{c :connection :as ctx} node]
     (println "SCROLL-VISIBLE: " node ", resolved: " (dom/resolve-node c node))
     (let [[ww wh] (evaluate ctx "[window.innerHeight, window.innerWidth]")
           [center-x center-y] (:center (bounding-box ctx node))
           scroll-x (int (- center-x (/ ww 2)))
           scroll-y (int (- center-y (/ wh 2)))]
       (println "SCROLL TO " scroll-x ", " scroll-y)
       (evaluate ctx (format "window.scrollTo(%d,%d)" scroll-x scroll-y))
       (let [{:keys [x y width height]} (bounding-box ctx node)
             [sx sy] (evaluate ctx "[window.scrollX, window.scrollY]")
             screen-x (- x sx)
             screen-y (- y sy)]
         (println "scroll at: " sx "," sy)
         {:x screen-x
          :y screen-y
          :center [(Math/round (double (+ screen-x (/ width 2))))
                   (Math/round (double (+ screen-y (/ height 2))))]})))))

(defn- node-object-id [{c :connection} node]
  (->> node (dom/resolve-node c) :object :object-id))

(defn- eval-node [{c :connection :as ctx} node-or-object-id & fn-def-strings]

(defn click
  ([node] (click @current-automation node))
  ([{c :connection :as ctx} node]
   (let [node (to-node-ref ctx node)]
     (visible ctx node)
     (let [{:keys [x y]} (scroll-into-view ctx node)
           event {:x x :y y :button "left" :click-count 1}]
       (input/dispatch-mouse-event c (assoc event :type "mousePressed"))
       (input/dispatch-mouse-event c (assoc event :type "mouseReleased"))

       ;; FIXME: Artificial slowdown, nodes that appear after clicking may be found
       ;; by a selector, but cannot be resolved (aren't sent to us by chrome yet?).
       ;; Implement a "dom" model that has all the nodes and keep resolved nodes
       ;; in the implementation. Always resolve a node from the "dom"
       (Thread/sleep 100)))))

(defn click-navigate
  "Click element and wait for navigation to be done."
