 
 (defn flip-team [app]
   (om/update! app :actions 0)
-  (if (= (:turn @app) :red-team)
+  (if (= (:turn @app-state) :red-team)
     (om/update! app :turn :blue-team)
     (om/update! app :turn :red-team)))
 
+(defn deselect-unit [owner]
+  (om/set-state! owner :selected-unit nil))
+
+(defn ball-in-front-of-unit? [ball-coords unit-coords]
+  (and
+   (=
+    (:x ball-coords)
+    (:x (:coords unit-coords)))
+   (or
+    (and
+     (= (:turn @app-state) :blue-team)
+     (= (:y (:coords unit-coords)) (- (:y ball-coords) 1)))
+    (and
+     (= (:turn @app-state) :red-team)
+     (= (:y (:coords unit-coords)) (+ (:y ball-coords) 1))))))
+
+(defn move-unit [app owner target]
+  (om/transact!
+   app
+   [:cells (:turn @app-state)]
+   (fn [units]
+     (map
+      #(if (= (:coords (om/get-state owner :selected-unit)) (:coords %))
+         ((fn []
+            (om/transact! app :actions inc)
+            (deselect-unit owner)
+            (cond (= (:actions @app-state) 2)
+                  (flip-team app))
+            {:coords target}))
+         %)
+      units))))
+
+(defn pickup-ball [app owner ball]
+  (om/transact!
+   app
+   [:cells :balls]
+   (fn [units]
+     (map
+      #(if (ball-in-front-of-unit? ball (om/get-state owner :selected-unit))
+         ((fn []
+            (println "PICKING UP BALL")
+            (om/transact! app :actions inc)
+            (cond (= (:actions @app-state) 2)
+                  (flip-team app))
+            {:coords (om/get-state owner :selected-unit)}))
+         %)
+      units))))
+
+(defn select-unit [app owner selected]
+  (om/set-state!
+   owner
+   :selected-unit
+   (first
+    (filter
+     #(= selected (:coords %))
+     ((:turn @app-state) (:cells @app-state))))))
+
+(defn handle-action [app owner actions]
+  (go
+   (loop []
+     (let [event (<! actions)]
+       (println event)
+       (case (:type event)
+         :select-unit   (select-unit app owner (:coords event))
+         :move-unit     (move-unit app owner (:coords event))
+         :deselect-unit (deselect-unit owner)
+         :pickup-ball   (pickup-ball app owner (:coords event)))
+       (recur)))))
 
 (defn board-view [app owner]
   (reify

   (<=
    (reduce
     +
     (map distance (vals target) (vals selected)))
    move-range)))

(defn turn-view [data owner]
  (reify

            (apply dom/tr #js {:className (border-top y)}
              (vec (for [x board-length]
                (om/build tile-view app
                  {:state
                   {:selected-unit (om/get-state owner :selected-unit)
                    :actions actions
                    :coords {:x x :y y}}})))))))
        (bench)))))

(om/root board-view app-state
