 (defn pan-observable [manager svg]
   (gesture-observable manager svg "panstart panmove"))
 
-
 (defn pan-deltas-observable [manager svg]
   (-> (pan-observable manager svg)
       (.bufferWithCount 2 1)

    svg))


;; Math

(def sqrt (.-sqrt js/Math))
(def tan (.-tan js/Math))
(def atan (.-atan js/Math))
(def pi (.-PI js/Math))
(def pi2 (/ pi 2))

(defn dist-sq [x y]
  (+ (* x x) (* y y)))

(def dist (comp sqrt dist-sq))

(defn vector-with-length [l x y]
  (let [factor (/ l (dist x y))]
    [(* factor x) (* factor y)]))


;; D3 magic

(defn project-displacement [d view-length]
  (let [project-positive-displacement
        (fn [d]
          (let [t (/ d view-length)]
            (* view-length
               (cond
                 (<= t 0.5) t
                 (<= 0.5 t 1) (+ 0.5 (/ (- t 0.5) 2))
                 (<= 1 t 1.5) (+ 0.75 (/ (- t 1) 4))
                 (<= 1.5 t 2) (+ 0.875 (/ (- t 1.5) 8))
                 (<= 2 t) 1))))]
    (if (pos? d)
      (project-positive-displacement d)
      (- (project-positive-displacement (- d))))))

(defn view-position
  "Given the actual position of a node (in world coordinates), return the
  position of the node in screen coordinates according to the state."
  [state x y]
  (let [{:keys [view-width view-height camera-x camera-y]} state
        view-center-x (/ view-width 2)
        view-center-y (/ view-height 2)
        view-radius (dist view-center-x view-center-y)
        x-displacement (- x camera-x)
        y-displacement (- y camera-y)
        r (dist x-displacement y-displacement)
        projected-r (project-displacement r view-radius)
        projected-x (* x-displacement (/ projected-r r))
        projected-y (* y-displacement (/ projected-r r))]
    {:x (+ view-center-x projected-x)
     :y (+ view-center-y projected-y)}))

(defn view-radius [state x y]
  (let [{:keys [view-width view-height camera-x camera-y]} state
        view-center-x (/ view-width 2)
        view-center-y (/ view-height 2)
        view-radius (dist view-center-x view-center-y)
        r (dist (- x camera-x) (- y camera-y))
        t (/ r view-radius)]
    (+ min-radius (* (- max-radius min-radius)
                     (cond
                       (<= t 0.5) 1

                           e1-center (.-center e1)
                           e2-center (.-center e2)]
                       (if (= (.-type e2) "panstart")
                         (math-vec 0 0)
                         (math-vec (- (.-x e1-center) (.-x e2-center))
                                   (- (.-y e1-center) (.-y e2-center)))))))))

(defn move-camera-on-pan! [manager current-state]
  (.subscribe
    (pan-deltas-observable manager (:svg @current-state))
    (partial move-camera! current-state)))

;; Gestures - swipe

