 (declare Palette)
 (declare PaletteWidget)
 
-(defn color-update [comp active-color closure-comp]
-  (om/transact! comp
-    `[(color/update {:color/id ~(:color/id active-color)
-                     :color/hex ~(.getColor closure-comp)}) :palette]))
+(defn widget-input-elem [comp]
+  (aget (query "input" (getElement (dom/node comp))) 0))
+
+(defn color-update
+  ([comp]
+   (let [{:keys [:palette-widget/active-color
+                 :palette-widget/closure-comp]} (om/props comp)]
+     (color-update comp active-color closure-comp (.getColor closure-comp))))
+  ([comp active-color closure-comp color-hex]
+   (when (not= color-hex (:color/hex active-color))
+     (om/transact! comp
+       `[(color/update {:color/id  ~(:color/id active-color)
+                        :color/hex ~(.getColor closure-comp)}) :palette]))))
 
 (defn color-remove [comp {:keys [color/id] :as color} e]
   (.preventDefault e)

(def color-adder (om/factory ColorAdder))

(defn handle-action [comp e]
  (let [{:keys [palette-widget/active-color palette-widget/face-classes-by-color-type]} (om/props comp)
        hex-temp (util/target-color e)]
    ;; TODO refactor this so its in the state, its wasteful to calculate this on each run through, could maybe even use the element references themeselves
    (let [{:keys [bg-faces fg-faces]} face-classes-by-color-type
          color-editable-selector (str ".color-" (:color/id active-color))
          [code-bg-selector face-bg-color-selector] (selectors-for-colorize bg-faces :face/color-bg)
          [code-fg-selector face-fg-color-selector] (selectors-for-colorize fg-faces :face/color-fg)]

      ;; TODO combine these
      (colorize-faces color-editable-selector "background-color" hex-temp)

      (when-not (empty? fg-faces)
        (colorize-faces code-fg-selector "color" hex-temp)
        (colorize-faces face-fg-color-selector "background-color" hex-temp))

      (when-not (empty? bg-faces)
        (colorize-faces code-bg-selector "background-color" hex-temp)
        (colorize-faces face-bg-color-selector "background-color" hex-temp)))))

(defui PaletteWidget
  static om/IQuery

  (:require [goog.style :refer [setStyle]]
            [goog.events :as gevents]
            [goog.array :refer [forEach]]
            [goog.dom :refer [getActiveElement getDocument getElement getElementsByTagNameAndClass]]
            [om.dom :as dom]
            [om.next :as om :refer-macros [defui]]
            [koeeoadi.util :as util]
